JavaScript’s Basic Idea Of Hoisting

Deepa Jarout
3 min readAug 11, 2022

--

Hoisting In JavaScript

In JavaScript, hoisting is a behavior where a function or variable can be used before declaration.

hoisting
hoisting

The output of the program as mentioned above is undefined, but it runs. The program as mentioned earlier acts in the following ways:

hoisting

Since the variable myName is just declared and has no value, it is given an undefined value.

Visit JavaScript Variables if you want to know more about variables.

The function and variable declarations are added to memory during the build phase, despite the fact that hoisting makes it appear as though the declaration has moved up in the programme hierarchy.

Variable Hoisting

When it comes to variables and constants, the keyword var is hoisted, but let and const do not permit hoisting.

variable hoisting
variable hoisting

Variable b is used previously to being declared in the case above. The program works, and output 10 is shown. As it operates, the program:

variable hoisting
variable hoisting

However, initializations are not hoisted in JavaScript.

hoisting

The above program behaves as

In the build stage, only the declaration is copied to memory. As a result of the variable being printed without initialization, its value is undefined.

f a variable is used with the let, const keyword, that variable is not hoisted. For example,

Function Hoisting

A function can be called before declaring it. For example,

function hoisting
function hoisting

The function sayHi is called before it is declared in the previous code, and the output is displayed. Hoisting is to cause for this.

However, because only declarations are hoisted, an error happens when a function is used as an expression. the following;

function expression with let
function expression with let
function expression with var
function expression with var

Conclusion

Hoisting in JavaScript comes with a number of restrictions, so it’s usually advised to use strict mode or declare all your variables at the beginning of the file to prevent misunderstanding.

--

--

Deepa Jarout

I am Software developer.I like problem solving, traveling, photography, dancing, video games, conversation.I like to explore new places with different tradition