JS Tutorial



JS HOISTING


JavaScript Hoisting 🚀

Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their containing scope during the compile phase, before the code has been executed. This concept can lead to some surprising results in your code.

🔼 Hoisting with var

In JavaScript, variables declared with var are hoisted to the top of their function or global scope, but their initialization (value assignment) is not.

// Example 1: Hoisting with var
console.log(myVar); // undefined (hoisted declaration, but not initialized)

var myVar = 5;
console.log(myVar); // 5 (after initialization)

🔼 Hoisting with let and const

Unlike var, variables declared with let and const are also hoisted, but they remain in the "temporal dead zone" until the code execution reaches them. Accessing them before initialization will result in a ReferenceError.

// Example 2: Hoisting with let and const
console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization

let myLet = 10;
console.log(myLet); // 10 (after initialization)

console.log(myConst); // ReferenceError: Cannot access 'myConst' before initialization
const myConst = 20;
console.log(myConst); // 20 (after initialization)

🔼 Hoisting with Functions

Function declarations are also hoisted. Unlike variables, function declarations are hoisted with both their definition and body.

// Example 3: Hoisting with function declarations
myFunction(); // "Hello, world!" (function is hoisted)

function myFunction() {
  console.log("Hello, world!");
}

🔼 Hoisting with Function Expressions

However, function expressions are only hoisted with their variable declaration, not the function definition. This can lead to unexpected results when you try to call a function before it's defined.

// Example 4: Hoisting with function expressions
myFunc(); // TypeError: myFunc is not a function

var myFunc = function() {
  console.log("This won't work until it's defined!");
};

myFunc(); // "This won't work until it's defined!" (after initialization)

🎮 Interactive Example

Click to see how hoisting works with variables and functions:

📘 Summary

  • var: Declaration is hoisted, but initialization is not.
  • let & const: Hoisted, but remain in the "temporal dead zone" until they are initialized.
  • Function declarations: Hoisted with both definition and body.
  • Function expressions: Only the variable declaration is hoisted, not the function body.
Tip: Always declare variables and functions at the top of your code to avoid confusing hoisting behavior.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review