A JavaScript guide for Beginners.

Hoisting in JavaScript ..!

Aditya Shetty
2 min readMay 14, 2020

Hoisting: Moving variable and function declarations on top of the code

Hoisting:

Hoisting by definition suggests moving variable and function declaration on top of the code.

What happens in fact is JavaScript engine sets up memory space for variable and function declarations even before the line by line execution of code is started.

Fig 1.1: Block diagram representing of how JavaScript Engine takes care of Hoisting

The concept of Hoisting is not just limited to JavaScript.

The following snippets will give you a better understanding of how Hoisting works in JavaScript while code execution, that may otherwise have been an error in most of the programming Language (if compiler is not built to hoist before execution).

Fig 2.1: Snippet 1

The expected output for above snippet in JavaScript (JS engine performs hoisting) does not vary from other programming language (Compilers which do not have hoisting).

Fig 2.2: Output for Snippet 1 execution

Hoisting Example:

Fig 3.1: Snippet 2

If you follow the execution flow with respect to physical code you might feel the code execution must result in error.

But…

Fig 3.2: Output for Snippet 2 execution

During the interpretation (line by line execution) of the code, when the control reaches line no. 5 it looks for declaration of function b() in memory space.

This memory space is setup by the JavaScript engine even before the interpretation of code starts as represented in Fig 1.1.

Hoisting can also be seen as a compiler optimization in view of various program compilers.

--

--