Sitemap
Sridhar Maskeri

Sridhar Maskeri

SSE | TypeScript | React | Node | Next Js | Designer

Hoisting 🚩 in JavaScript!

3 min readOct 5, 2022

--

Press enter or click to view image in full size
Hoisting in Js

Let’s understand what is hoisting in JavaScript and how does it work with the help of some examples 🌟

Press enter or click to view image in full size
Example 1

The above code is a normal JavaScript program, whose output is:

  • Sridhar Maskeri
  • 7

What happens if we call the function while also attempting to print the variable before declaring them? 🤔

Press enter or click to view image in full size
Example 2

Now the output is:

  • Sridhar Maskeri
  • undefined

The phenomenon that occurs in the above example is called as Hoisting 🚩 in JavaScript.

Hoisting🚩 in JavaScript allows us to access variables and functions even before declaring or initialising them.

The Creation phase and the Execution phase are the two distinct phases that make up each Execution Context, and each has its own distinct duties.✨

The JavaScript engine will begin the Global Creation phase by :

  1. Creating a global object.
  2. Creating an object called “this”.
  3. Setting up memory space for variables and functions.
  4. Assigning variable declarations a default value of “undefined” while placing any function declarations in memory.

In plain English, this means that the code is first scanned, the variables and functions are given a reserved area in the memory, and only then is the line-by-line execution of the code carried out.

Get Sridhar Maskeri’s stories in your inbox

Join Medium for free to get updates from this writer.

This is the reason why the value of x is undefined in Example 2.

Now let’s try to print the value of x after it has been initialised. 🤠

Press enter or click to view image in full size
Example 3

Yes you got it right 👏, now the output will be:

  • undefined
  • 7

Now let’s try to print the value of a variable that is never initialised or declared. 🤠

Press enter or click to view image in full size
Example 4

Output :

  • Sridhar Maskeri
  • Here we get an error : Uncaught ReferenceError: x is not defined

Here we do not get undefined since the variable x is never declared or initialised in the entire program. 😯

Let’s now examine what would happen if the function getName() was an arrow function. 🧐

Press enter or click to view image in full size
Example 5

Output :

We get an Error : Uncaught TypeError : getName is not a function

This is because the arrow function acts as a variable rather than a function. Hence it initially stores the value undefined. 😯

I hope you at least have a rudimentary understanding of hoisting now that you know what it is and how it works in JavaScript. 🤗

Video Reference : https://www.youtube.com/watch?v=Fnlnw8uY6jo&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=4

Happy Coding :) 🙌

--

--

Sridhar Maskeri
Sridhar Maskeri

SSE | TypeScript | React | Node | Next Js | Designer