Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / Javascript
Technical Blog

JavaScript var Hoisting

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
18 Jan 2013CPOL2 min read 5.4K   1  
JavaScript var Hoisting

At a quick glance what do you think the value of ‘y’ will be at each alert?

<script src="https://gist.github.com/1176158.js?file=varhoistingblogpostexample1.js"></script>

When I was first beginning to work in javascript my guess would’ve been: ‘alert 1: 1’, ‘alert 2: 1’, and ‘alert 3: 2’; thinking that the global value from before the function would carry into the function until it is reassigned.

The answer is instead ‘1, undefined, and 2’. This result comes about because of an interesting behavior of javascript that I had not come across until yesterday while reading ‘Javascript Patterns’. The behavior is that the javascript engine takes two passes over each function scope while running the script.

In the first pass the function is parsed and all local variables are moved to the top of the function. And the second pass runs it. So in reality the script looks like this by the time it is run:

<script src="https://gist.github.com/1176159.js"> </script>

Notice that ‘var y’, and not ‘var y = 2’ was moved to the top of the function. By declaring an unset local variable at the top of the function the global ‘y’ variable is overwritten, causing ‘alert 2’ to be undefined.

In theory as a javascript developer you shouldn’t be polluting the global object with variables such as ‘y’ anyways, so this issue should not crop up for you. But it is good to know how the javascript engine actually parses your scripts. This is a good case for going ahead and just putting all of your local variables at the top of your function, since the javascript engine is going to do it anyways. This will reduce unexpected behaviors and is considered a best practice.

If you are interested looking further into this type of behavior in javascript checkout this blog post, which goes more in depth over javascript scope behavior: JavaScript-Scoping-and-Hoisting. Also pick up the book ‘Javascript Patterns’ by Stoyan Stefanov. Chapter 2 alone is worth twice the book’s listed price.

This article was originally posted at http://jdonley83.github.com

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Element Fusion
United States United States
I am a web developer for Element Fusion living in Oklahoma City, OK. I've been developing in .Net web technologies since the summer of 2009. I enjoy working in Asp.Net MVC along with tinkering with other new web technologies.

Comments and Discussions

 
-- There are no messages in this forum --