Hoisting in JS

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

One of the advantages of JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code. For example:

The above code snippet is how you would expect to write the code for it to work. Now, let’s see what happens when we call the function before we write it:

Even though we call the function in our code first, before the function is written, the code still works. This is because of how context execution works in JavaScript.

Hoisting works well with other data types and variables. The variables can be initialized and used before they are declared.

JavaScript only hoists declarations, not initializations.

The example below only has initialization. No hoisting happens so trying to read the variable results in ReferenceError exception.

Initializations using let and const are also not hoisted.

--

--

Developer with 3 yrs of industrial experience in developing scalable web applications.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.