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.
Unlike var, let respects {} blocks. The score inside the if block is isolated and does not interfere with the score outside.
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!)let variable 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.Can you access a 'let' variable before declaring it?
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).
You primarily use let in scenarios where data updates over time, such as pagination counters, timers, or live scores.
let currentPage = 1;
function fetchNextPage() {
currentPage += 1; // Safely reassigns the let variable
api.getData(currentPage);
}Test your understanding of let Keyword with these quick questions.
Question 1
What happens if you declare `let count = 0;` and then `let count = 1;` in the exact same scope?
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.
Unlike var, let respects {} blocks. The score inside the if block is isolated and does not interfere with the score outside.
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!)let variable 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.Can you access a 'let' variable before declaring it?
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).
You primarily use let in scenarios where data updates over time, such as pagination counters, timers, or live scores.
let currentPage = 1;
function fetchNextPage() {
currentPage += 1; // Safely reassigns the let variable
api.getData(currentPage);
}Test your understanding of let Keyword with these quick questions.
Question 1
What happens if you declare `let count = 0;` and then `let count = 1;` in the exact same scope?