Hoisting In JavaScript Applications

22 Jul

In JavaScript functions if you have variable declarations inside it is best to declare all of them in top of the function which is known as single var pattern. Reason for this is “Hoisting” in JavaScript applications.
Consider following code,

// antipattern
myname = "global"; // global variable
function func() {
console.log(myname); // "undefined" expected "global"
var myname = "local";
console.log(myname); // "local"

It is surprising to see that first alert prints “undefined” rather than the “global” as expected. The reason for this is that when you declare variables inside functions they get “hoisted” which means variable declaration is being moved to the beginning of the function. This is very confusing at first which leads to logical errors hence its best to declare variables and their initializations to the top of the function in JavaScript. So what is happening in first alert is that since “myname” variable declaration moved to the top and it’s initialized to undefined (as normally JavaScript does).
So the above code works as if it was implemented like this,

myname = "global"; // global variable
function func() {
var myname; // same as -> var myname = undefined;
console.log(myname); // "undefined"
myname = "local";
console.log(myname); // "local"
Leave a comment

Posted by on July 22, 2013 in Javascript



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: