0
0
Javascriptprogramming~5 mins

Hoisting with let and const in Javascript

Choose your learning style9 modes available
Introduction

Hoisting means JavaScript moves variable declarations to the top before running code. Understanding how let and const behave helps avoid errors.

When you want to declare variables that should not be accessed before their definition.
When you want to avoid bugs caused by using variables too early in your code.
When you want to use block-scoped variables safely.
When you want to understand why some variables cause errors if used before declaration.
Syntax
Javascript
let variableName = value;
const constantName = value;

let and const declarations are hoisted but not initialized immediately.

Accessing them before their declaration causes a ReferenceError due to the 'temporal dead zone'.

Examples
This causes a ReferenceError because x is in the temporal dead zone before declaration.
Javascript
console.log(x);
let x = 5;
This also causes a ReferenceError for the same reason as let.
Javascript
console.log(y);
const y = 10;
This works fine because a is declared before use.
Javascript
let a = 3;
console.log(a);
Sample Program

This program shows that trying to use let or const variables before they are declared causes errors. After declaration, they work fine.

Javascript
try {
  console.log(num);
} catch(e) {
  console.log('Error:', e.message);
}

let num = 7;
console.log(num);

try {
  console.log(pi);
} catch(e) {
  console.log('Error:', e.message);
}

const pi = 3.14;
console.log(pi);
OutputSuccess
Important Notes

var variables are hoisted and initialized with undefined, so no error occurs if accessed before declaration.

let and const are block-scoped and safer to use to avoid bugs.

Summary

let and const are hoisted but not initialized immediately.

Accessing them before declaration causes a ReferenceError due to the temporal dead zone.

Always declare let and const variables before using them.