[JavaScript] Hoisting

Hoisting” means to lift someone or something to a higher place. JavaScript lifts (hoists) variables and functions to the top.

1. Scope

Variables in most programming languages are scoped in blocks { }. JavaScript does not have block scope. Instead, it has function scope.

{
  var i = 10;
}
alert(i);

It returns “10” even though “i” is defined in a block.

But if the variable is defined in a function, it is local to the function.

function doSomething(){
  var i = 10;
}
alert(i);

You will get an error “i is undefined”.

 

2. Variable Hoisting

Now you know variables are local in a function. But JavaScript engine hoists all local variables to the top. What does it mean?

(function () {
  alert(i); // undefined or 10 ???
  var i = 10;
})();

You will see the alert box with “undefined”. What does it mean? What has happened here?

Hoisting only lifts the declaration, not the value. The previous code is much like the following:

(function () {
  var i;
  alert(i); // undefined
  i = 10;
})();

This feature can make your code quite interesting when the local variable is mixed with the global one.

var i = 5; // global
(function () {
  alert(i); // undefined
  var i = 10;
  alert(i); // 10
})();

You might think the first alert(i) will show “5”. But it displays “undefined” because the local variable declaration is hoisted.

Note that only the declaration is hoisted; the value is not hoisted.

 

3. Function Hoisting without var

Functions are also hoisted in a global or function scope. You can call the function even before it is defined.

(function () {
  alert(add(2, 3)); // 5

  function add(x, y) {
    return x + y;
  }
})();

 

4. Function Hoisting with var

But if functions are assigned to variables using “var“, only declarations are hoisted. Function implementation is not hoisted.

alert(add(2, 3)); // error

var add = function (x, y) {
  return x + y;
}

alert(add(3, 4)); // 7

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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