Javascript Hoisting Explained

A common question that people have when learning Javascript is what the difference is between a function expression and a function declaration.
For example:

Function Expression

var x = function(){
  return true;
};

 vs

Function Declaration

function x(){
  return true;
};

The key difference between these two patterns has to do with variable hoisting. Variable hoisting is something that happens when your Javascript is “compiled” by the browser. The browser reads your code and grabs all of your function and variable declarations and moves them to the top of their scope.

Like this:

function(){

  var a = true;
  var b = true;

  var c = function(){
    return true;
  };

  function d(){
    return true;
  };

}();

Gets “compiled” and becomes this for when the code is executed:

function(){

  function d(){
    return true;
  };
  var a;
  var b;
  var c;

  a = true;
  b = true;

  c = function(){
    return true;
  };

}();

As you see, all of the function and variable declarations get put at the top of their current scope. Declarations move to the top but all expressions occur where the code is written.

 A Common Gotcha:

The following code throws an error:

function(){

  a();
  b();//Uncaught TypeError: undefined is not a function

  function a() {
    return true;
  };
  var b = function(){
    return true;
  };

}();

The reason we get an error is because var b is hoisted but not the function that is on the right side of the expression.

Here’s what that code looks like at runtime with its declarations hoisted:

function(){

  function a(){
    return true;
  };
  var b;

  a();
  b();//Uncaught TypeError: undefined is not a function

  b = function(){
    return true;
  };

}();
 
189
Kudos
 
189
Kudos

Now read this

Closure and For Loops

Note: If you don’t understand Javascript closures then I recommend you first check out this blog post. When I was interviewing for a job in San Francisco I was asked to fix the following code: for (var i = 0; i < 5; i++) {... Continue →