JavaScript Hoisting

You may heard of JavaScript Hoisting and read a lot of articles about it already. Here I just want to make my own summarization to help folks to better understand JavaScript. So, let's start:

In JavaScript, there are 2 types of hoisting: variable hoisting and function hoisting.

1) Varaible Hoisting

A simple example:

var baz = 1;
function foo() {
  console.log(baz); // undefined
  var baz = 10;
  console.log(baz); // 10
}

same as:

var baz = 1;
function foo() {
  var baz;
  console.log(baz); // undefined
  var baz = 10;
  console.log(baz); // 10
}

A slightly complex example:

var foo = 1;
function bar() {
  if (!foo) {
    var foo = 10;
  }
  console.log(foo);
}
bar();//10
console.log(foo); //1

same as

var foo = 1;
function bar() {
  var foo;
  if (!foo) {
    var foo = 10;
  }
  console.log(foo);
}
bar();//10
console.log(foo); //1

Explain:

In JavaScript, all variables and parameters declared inside a function are visible everywhere within that function, even before the variable has been declared. That's because within current scope, regardless of where a variable is declared, it will be hoisted to the top.

2) Function Hoisting

function test() {
  foo();
  console.log(foo); // function foo() {}
  function foo() {};
}

Explain:

We see this very common in JavaScript code about calling a function before it has been declared. The reason is that regardless of where a function is placed, it is moved to the top of the scope in which it is defined(hoist) .

The statement:
      function foo() {}; is actually the same thing as
      var foo = function foo() {};

So The name 'foo' is hoisted, but the body is left behind, to be assigned during execution.

Looks similar to variable hoisting, right?

More on this.

In the following two cases, only "foo" gets hoisted, not the function body.

foo(); //TypeError
var foo = function () {};
var foo = function bar() {};

So, if you call foo() before the statements. you will get a TypeError "foo is not a function".

Yang Zhao

Read more posts by this author.


Comment