Variable Hoisting in JavaScript

Wazeed Mohammad
2 min readJun 15, 2021

If you are coding in JavaScript for a while then you must have heard the concept called hoisting. You might have known this concept but did you know what really happening behind the scene. Let’s jump in.

Let’s start with an example. What will be the output here?

Example:

Hoisting in JavaScript

It print’s undefined. Confused! Instead of throwing an error why the variables a and b prints undefined? How these variables are accessible before it’s declarations?

This behavior of JavaScript is called hoisting.

As per the definitions available over the internet hoisting means variable declarations and function declarations are moved to top of the code. That’s why variables and functions are accessible prior to it’s declarations.

Concept wise this is fine but that’s not happening actually. Let’s take a deep dive.

What is JavaScript Engine?

A JavaScript engine is a program resides inside the browser, which compiles and execute the JavaScript code. JavaScript engine go through the code in two phases. Memory creation phase and Execution phase. In Memory creation phase it goes through code line by line and if it finds any variable declarations, initializes them to undefined. That means before JavaScript engine moves to execution phase the variables will have their default values. That’s why in the above example output printed as undefined.

Let’s debug the above example code inside the developer tools to get more clarity on hoisting.

variable hoisting
Variable Hoisting

Here I’ve added a debugger at the first line(that means before execution starts) and checking the values of a and b. The values of a and b (highlighted in green) shows how JavaScript engine store the values of variables in Memory creation phase before executing the code.

That’s all about variable hoisting.

Try your own examples, debug and see how JavaScript engine behaves.

I hope now you got an idea about hoisting. Thanks for reading :)

--

--