Geeks With Blogs
Ken Dason

In JavaScript, hoisting moves all declarations to the top of their scope.  As JavaScript is function-scoped, this means all declarations are moved to the start of the function despite the fact that they may be defined somewhere else with the body of the function. 

Hoisting of variables

Example 1: The variable person is declared globally and is thus available when accessed from within the notify function.

var person = "John Doe";

function notify() {
   console.log("Notifying " + person);
}

notify();

Running this code results in the following output in the console window:

Notifying John Doe

Example 2: Change the value of person within the notify function.

var person = "John Doe";

function notify() {
   console.log("Notifying " + person);
   person = "Mickey Mouse";
   console.log("Notifying " + person);
}

notify();

Running this code results in the following:

Notifying John Doe
Notifying Mickey Mouse

No surprises here – this is just as expected.

Example 3: Set a new local person variable within the notify function to the value "Mickey Mouse".

var person = "John Doe";

function notify() {
   console.log("Notifying " + person);
   var person = "Mickey Mouse";
   console.log("Notifying " + person);
}

notify();

When this code is executed, we console window shows these results:

Notifying undefined
Notifying Mickey Mouse

Why does this happen? Even though the local variable person is defined in the middle of the function block, the variable declaration is hoisted to the top of the function and masks the global person variable.  As the value of the local variable is not yet set when the first console.log method is executed, we get undefined.

Example 3 is similar to the code below which has the local person variable declared at the very start of the function block.

var person = "John Doe";

function notify() {
   var person;
   console.log("Notifying " + person);
   person = "Mickey Mouse"; 
   console.log("Notifying " + person);
}

notify();

Hoisting of functions

Here, the hitSnoozeButton function is declared after it is called.  As function declarations are also hoisted to the top, we can have statements referring to it even prior to its declaration.

function sleepLonger() {
   hitSnoozeButton();
   function hitSnoozeButton() {
      console.log("Waiting for 10 more minutes before sounding alarm...");
   }
}

sleepLonger();

This code execution results in output shown below:

Waiting for 10 more minutes before sounding alarm...

Posted on Saturday, July 13, 2013 9:51 PM JavaScript | Back to top


Comments on this post: JavaScript Hoisting

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Ken Dason | Powered by: GeeksWithBlogs.net | Join free