What is hoisting in Javascript? Also, provide an example of hoisting.

Because Javascript has Function Scope, this also means that variables declared within a function are visible anywhere in that function. So, if a variable is declared in the middle or even at the very bottom of a function, that variable will still be visible even at the top of the function – meaning that the variable will be visible above its declaration. But, this does not mean that assigned values will still remain associated with the variable – it’s just that the variable name will be recognized starting from the very beginning of the function.

This is an interesting feature of Javascript known as hoisting, because it is as if Javascript is “hoisting” (which means to move up) the variable declaration to the top of the function. And it is best to explain this feature through an example:

Example of Hoisting in Javascript


// global variable
var testVar = "I'm a global";

function example( )
{
  alert(testVar);  //what does this line alert?
  
 /*local variable with same name as the global
    declared outside the function
 */

  var testVar = "I'm a local var";
  alert(testVar);  // what does this line alert?
}

example( );

The question is what do the lines above output to the page?

If you guessed that the first one outputs “I’m a global” and the second one outputs “I’m a local var”, then you would unfortunately be wrong. Because of the way that function scope works, the code above will actually output this:

undefined
I'm a local var

Here is what’s happening: the local testVar variable (the one declared in the example function) behaves as if it is defined throughout the entire function – even at the very top, because of the property of hoisting. This means that the global variable with the same name (“testVar”) is essentially hidden inside the function, because the local variable will take precedence over the global, and will be visible throughout the entire function.

So why would the first alert output “undefined” if the testVar variable is actually defined throughout the entire function? Well, remember we said that the value assigned to the variable will not also be moved up to the top of the function – so even though the variable is recognized at the top, it does not actually have a value associated with it until this line is executed:

var testVar = "I'm a local var";

You can think of our example above as being equivalent to this code – where the variable is declared at the top of the function, but the variable is not assigned an actual value until lower down in the function:


function example( )
{
  var testVar;
  
  alert(testVar);  //outputs "undefined"

  var testVar = "I'm a local var";
  alert(testVar);  // outputs "I'm a local var"
}

example( );

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.