Tuesday, October 17, 2017

Hoisting in JavaScript

Due to it's somewhat awkward behavior, concepts in JavaScript is little tricky to understand. Hoisting is one of them. Hoisting can be divided in to two. Variable hoisting and function hoisting. We'll first look at variable hoisting.


Variable hoisting


If you execute below line you'll get a ReferenceError.


This is because definition for value1 is not exist. Now consider below.


Even though value1 is defined after line1, still it'll say value1 is undefined. But won't show the value. This is because JavaScript interpreter goes through the file and "hoist" the variable definitions on top of the function. But value assignment happens later.

you must have expected var1 to print 1 since it was defined in the outer scope. But due to function hoisting and functional level scoping it will print undefined. But since var2 doesn't exist in current scope, it will get value 2 and print it. This is the reason it's recommended to declare all variables on top of a function.


Function hoisting


Unlike variables, functions doesn't just hold the function name, it holds the actual function definition.


something to remember is that function hoisting happens only for function defintions. Not function expressions.

Here the variable func2 will be defined but not the function definition. (TypeError). JavaScript only has function level scoping.

function declarations and variable declarations are always moved('hoisted') invisibly to the top of their containing scope by the interpreter. Function parameters and language defined names.


Resources

http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook