JavaScript Hoisting

JavaScript Hoisting

·

2 min read

hoist

What is hoist in JavaScript? Let's look at the first example.

console.log(add);

function add() {

}

Can you guess what the console.log prints out? We know that JavaScript is an interpreted language, which means that basically the engine executes code line by line. So according to this, the above code should throw an error because the add function is defined after being used.

But when we runs the code, we should have a [Function: add] printed out properly. So why? This is the hoist comes in. To put it simply, hoist in JavaScript is that before executes codes, JavaScript engine will scan the code first, and then move the variable declaration and function definition to the top of its current scope. So becuase of this, the add function definition was executed first, and then the console.log runs properly.

There are two types of hoist, let see them one by one.

var

The variable defined by var keyword will be hoisted. But note that only varibale declaration part is hoisted, the varibale assignment part is not included.

console.log(a); // undefined
var a = 100;

The above code is actually equivalent like below.

var a; // hosited part
console.log(a);
a = 100;

The let or const varibale is hoisted too but JavaScript engine doesn't allow to access it before initialization.

console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 100;

console.log(c); // ReferenceError: Cannot access 'c' before initialization
const c = 100;

This is different from accessing not exists variables.

console.log(d); // ReferenceError: d is not defined

function

Functions defined by function keyword will be hoisted too. This time, the whole function will be hoisted, so we can call the function first and it will runs properly.

console.log(add); // [Function: add]
function add(a, b) {
  return a + b;
}

Note anonymous functions or arrow functions will not be hoisted. If we use var keyword to define them, then it will be hoisted according to the rules of var keyword hositing.

console.log(add); // undefined
var add = function(a, b) {
  return a + b;
}

scope

Variables will only be hoisted to its current scope, not global scope.

var temp = "hi"
function display(){
  console.log(temp) // undefined, because of next line variable be hoisted up to top of display function
  var temp = "bye" 
}
display()

Same things happen to functions.

function outer() {
  inner(); // will use the next line hosited one
  function inner() {
    console.log("outer inner");
  }
}

outer(); // outer inner

function inner() {
  console.log("inner");
}