Nam Mai

I am software engineer. Currently doing more in front-end, focused in React and C#.

Javascript Hoisting

01 Dec 2017 » javascript

Hoisting is an action of javascript interpreter which moves all declarations to the top.


Why hoisting matters? Consider the example shown below.

 foo();
 var foo = function() {
   alert('Hi');
 }

This example generates an exeption due to calling non-function variable. Because the code shown above actually translates to the following code.

var foo;
foo();
foo = function() {
  alert('Hi');
}

How about the following example?

foo();
function foo() {
  alert('Hi');
}

This example will work due to function declaration hoisting.


Quiz

What is the result of executing this code?

function test() {
   console.log(a);
   console.log(foo());

   var a = 1;
   function foo() {
      return 2;
   }
}

test();

Related Posts