javascripthoistingexecutioncontext

Confusion about Javascript Hoisting


I thought I grasped the concept of hoisting, but the code below got me confused. How does it return 1? Will the second example() function be hoisted above the first one?

function example() {
  return 9;
}

console.log(example());

function example() {
  return 1;
}

If a function declaration is hoisted in a compilation phase and a function expression is executed in the execution phase. How come the code below returns 7? Is it simply due to example expression being declared first?

var example = function() {
  return 7;
}

console.log(example());

function example() {
  return 0;
}

Thank you in advance!


Solution

  • The reason why var example = function() is getting called instead of function example() is the order of hoisting.

    Functions are hoisted first, then variable declarations, per ECMAScript 5, section 10.5 which specifies how hoisting happens.

    Read more here: Order of hoisting in JavaScript