
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 withlet
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, unlikevar
.
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.
- Is limited to a block
- 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.