Let’s focus on let in JavaScript in detail.


πŸ”Ή let in JavaScript

The let keyword is used to declare block-scoped variables in JavaScript.
πŸ‘‰ Introduced in ES6 (2015) to fix issues with var.


1️⃣ Syntax

let variableName = value;

Example:

let age = 20;
let name = "Raj";

2️⃣ Features of let

βœ… Block Scope

  • A variable declared with let is only available inside the block { } where it is declared.
{
  let x = 10;
  console.log(x); // 10
}
// console.log(x); ❌ Error (x not accessible outside block)

βœ… Cannot Redeclare in Same Scope

  • You cannot redeclare the same variable within the same block.
let a = 5;
// let a = 10; ❌ Error: Identifier 'a' has already been declared
a = 10;   // βœ… Reassignment is allowed
console.log(a); // 10

βœ… Reassignment is Allowed

  • Unlike const, variables declared with let can be reassigned.
let city = "Delhi";
city = "Mumbai"; // βœ… Allowed
console.log(city); // Mumbai

βœ… Hoisting with Temporal Dead Zone (TDZ)

  • let is hoisted but not initialized.
  • Using it before declaration causes an error.
// console.log(x); ❌ ReferenceError (TDZ)
let x = 100;
console.log(x); // 100

βœ… Works Better in Loops

  • let creates a new variable for each loop iteration, unlike var.
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);
}
// Output: 0, 1, 2  βœ… (correct behavior)

If we used var, all outputs would be 3.


3️⃣ When to Use let?

  • When you need a variable that:
    • Is limited to a block { }.
    • May be reassigned later.
  • Example: counters, temporary values, loop variables.

βœ… Summary

  • Block-scoped (exists only inside { }).
  • Cannot redeclare in the same scope.
  • Can be reassigned.
  • Hoisted but in the Temporal Dead Zone until initialized.
  • Safer than var, preferred in modern JS.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *