Topic 9 of 87
let Keyword
Overview
let was introduced in ES6 (2015) to fix the problems with var.
Use let when you need to declare a variable that will change (reassign) its value later in the program, like a counter in a loop or a user's score in a game.
Syntax
Unlike var, let respects {} blocks. The score inside the if block is isolated and does not interfere with the score outside.
Block Scoping with let
javascript
let score = 10;
if (true) {
let score = 50; // This is a completely different variable!
console.log(score); // 50
}
console.log(score); // 10 (The original is safe!)Common Pitfalls
- Trying to re-declare a
letvariable in the same scope throws a SyntaxError. (e.g.,let x = 1; let x = 2;will crash your app). This is actually a good thing, preventing accidental overwrites.
Interview Questions
Q:
Can you access a 'let' variable before declaring it?
A:
No. Unlike 'var', which gives 'undefined', trying to access a 'let' variable before its declaration throws a ReferenceError due to the Temporal Dead Zone (TDZ).
Real-World Example
You primarily use let in scenarios where data updates over time, such as pagination counters, timers, or live scores.
example
javascript
let currentPage = 1;
function fetchNextPage() {
currentPage += 1; // Safely reassigns the let variable
api.getData(currentPage);
}Check Your Knowledge
Test your understanding of let Keyword with these quick questions.