DEV Community

Kush
Kush

Posted on • Updated on

Hoisting

Hoisting is a behaviour in JavaScript when a declaration is moved to the top of it's enclosing scope no matter where in the scope you've declared it.


Var

Let's understand this with a simple example:

var x = 11;

callMeAnytime();

function callMeAnytime() {
  x = 9;                     
  console.log(x);
  var x;
};

console.log(x);
Enter fullscreen mode Exit fullscreen mode

Many/Some of us would think this block of code will throw an error on execution but that's not what going to happen. What's exactly going to happen is:

var x = 11;

callMeAnytime();             //function declaration is 'hoisted'

function callMeAnytime() {
  x = 9;                     
  console.log(x);            //9
  var x;                     // variable declaration is 'hoisted' to
};                           // the top of the callMeAnytime function

console.log(x);              // 11
Enter fullscreen mode Exit fullscreen mode

You can think declaration as a flag and Javascript as the one who hoist the flag. On hoisting, flag reaches top. Isn't it?

Flag Hoisting GIF
Source


Let and Const

When it comes to let and const, hoisting is bit confusing and I'll tell you why?

Consider below examples.

console.log(x);

let x = 11;               // or, const x = 11;
Enter fullscreen mode Exit fullscreen mode

On executing, you get ReferenceError: Cannot access 'x' before initialization and you going to think hoisting doesn't happen in let and const but that's not all. Let me clear this up in the next example:

console.log(y);
let x = 11;
Enter fullscreen mode Exit fullscreen mode

You get ReferenceError: y is not defined on executing and that's what makes the difference.

Here, JavaScript has no idea about the y variable is because it is not defined and isn't it obvious that we didn't define it? We've only defined x.

In the first code snippet, it says "cannot access before initialization" and not "is not defined" and that means Javascript has considered hoisting of let/const without a default initialization.

The state between execution where let/const variables are hoisted and its existence is known but not accessible as it's not initialized yet, is called TEMPORAL DEAD ZONE** (Sounds fancy.. Isn't it?).

Mike Shinoda being fancy
Source


let/const are hoisted WITHOUT a default initialization and var is hoisted WITH default initialization of undefined.

Top comments (0)