Hoisting in JavaScript

Introduction

In this Blog, we will cover Hoisting in JavaScript. 

What is Hoisting?

In JavaScript, hoisting is a behavior in which variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This allows you to use variables and functions before they are actually declared in your code.

Note. It's important to note that only the declarations are hoisted, not the initializations or assignments. This means that while you can reference a variable or function before it's declared, any actual assignment or value assignment will occur in the order they appear in the code.

Variables Declared With var

Variables declared with var are hoisted and initialized with the value undefined. This means you can access and reference them before the actual declaration in your code.

Variables Declared With let

Variables declared with let and const are also hoisted, but they are not initialized with a value of undefined. Instead, they enter a "temporal dead zone" (TDZ) where trying to access them before their actual declaration will result in a runtime error.

Example

console.log(varValue); // Output: undefined
var varValue = "Hello";

console.log(letValue); // Error: Cannot access 'letValue' before initialization
let letValue = "World";

console.log(constValue); // Error: Cannot access 'constValue' before initialization
const constValue = "!";

Let's Understand With Real Life Scenario

Imagine you're getting ready for a road trip. You make a checklist of things to do before you hit the road, like packing your bags, checking the fuel level, and ensuring the car's tires are properly inflated. You start checking off items on your checklist even before you've completed every task.

In this analogy:

  • Your road trip checklist is like your JavaScript code.
  • Each task on the checklist is similar to a variable or function declaration.
  • Checking off tasks before completing them is like hoisting.

Here's the connection in code

console.log(task); // Output: undefined

var task = "Pack Bags";

console.log(task); // Output: Pack bags

The variable task is declared with the task "Pack bags", but it's not assigned a value until later. Just as you start checking items off your road trip checklist before finishing every task, the declaration is "hoisted" to the top, resulting in undefined at the first log. When the value is assigned, the second log prints "Pack bags. " So, similar to how you can start marking tasks off your road trip checklist even before you've fully completed them, in JavaScript, you can reference variables and functions before they're fully initialized due to hoisting.

Summary

In this blog, here we tried to understand what is Hoisting in JavaScript.