Thursday, March 22, 2012

Hoisting

Hoisting is one of the feature in JavaScript that puzzles many beginners and intermediate developers.  Hoisting is a feature wherein all the variables are moved to the outermost scope, which is function, in JavaScript.  This may sometimes result in seemingly strange behavior.

Before and after hoisting





The output of the above program is an alert with a value of 10.  Traditional logic would have lead us to believe that the value of alert should be undefined.  But because of hoisting the variable is moved to the top of function declaration.  Its important to realize that only the variable declaration is moved and not the initialization.
Recommendation: Always declare your variables at the top of the function scope.

Similar to variable hoisting we also have function hoisting.  Function hoisting has different behaviors based on the fact if the function is an expression or a declaration.

A function is an expression if it is assigned to a variable.  The assignment may also hold an anonymous or named function.   A function declaration is fully hoisted whereas a function expression has the hoisting behaviour of the variables as seen above.

Checkout the jsfiddle demo for a running application.


Watch out for next post where we will be demystifying "scope" in JavaScript.

3 comments:

Tekacademy.com – rajesh pillai - JavaScript Scope said...

[...] You can read more about hoisting here http://rajeshpillai.tekacademy.com/hoisting/ [...]

Siddhesh said...

Nice Post :)

hxxxld said...

vIvOlr exzjfkvpkcbt, [url=http://vlrzfwctsceu.com/]vlrzfwctsceu[/url], [link=http://zcicmlebrwbf.com/]zcicmlebrwbf[/link], http://jeymgxnghlud.com/