Variable Hoisting in Javascript

Vivek Sharma
The Startup
Published in
3 min readSep 13, 2020

--

Introduction:

This article is in continuation of my previous article: Javascript Variable Scopes

Hoisting is a tricky and very important topic in javascript. Lot of questions asked in javascript interviews are based on hoisting.

In this article, we will go through variable hoisting in javascript and see how it affects the desired output.

So, let’s not wait further and dive into concept of hoisting.

What is Variable Hoisting?

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

This means when javascript engine compiles your code, all variable declarations using var are lifted to the top of their functional/local scope (if declared inside a function) or to the top of their global scope (if declared outside of a function) regardless of where the actual declaration has been made.

Basically, it gives us an advantage that no matter where variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. It allows us to use variables before it is declared in our code.

The following example declares variable studentName and assign value John to it:

--

--

Vivek Sharma
The Startup
0 Followers
Writer for

Frontend Developer | Web Developer | Mobile App Developer | Freelancer | Blogger | Techie