What is Hoisting in javaScript ?

Shivam Gupta
2 min readDec 9, 2018

--

Hoisting in Js

When javaScript compile your code variables declaration using var & function declarations moved to top of your code.
(moving means hoisted)

  1. If variable defined inside function or local block so it moves top of the them.
  2. If declared outside of function so move to top of the global scope.

So no matter anywhere you declare variable it will automatically be to top of the code, is called HOISTING.

Lets understand it by example —

a. Here firstName is not declare yet so error
b. Now see what happens not give reference error

In case b what happen variable value defined after console still not give reference error because what actually happen when compile code —

var firstName;
console.log(firstName);
firstName = “ Shivam ”

So it gives undefined (Variable declared but value not assigned )not a reference error.

So in Hoisting only variable declaration moves to the top not actual value;

What actually happen in hoisting —

sayHello(“Hello Sir !”)
function sayHello(message) { console.log(message) }

Output- Hello Sir

is that your function and variable declarations are added to memory during the compile phase.

In the example above, because our function declaration was added to memory during the compile stage, we’re able to access and use it in our code above where it is typed.

Guess the output of this method —

Hoisting Example

So when we call method — printName() so what is output ?
a) Shivam Gupta
b) undefined

c) Saurabh

It will output undefined why ? because of hoisting. Looking tough to understand lets see what actually happen .

while compile this javascript code it will look like —

when declare variable block level so it declared to the top of block

Cool ! If you like this article give a clap :)

--

--

Shivam Gupta
Shivam Gupta

Written by Shivam Gupta

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

No responses yet