Topic 7 of 37
The let Keyword
Overview
Introduced in ES6 (2015), 'let' allows you to declare block-scoped local variables, optionally initializing them to a value. It solves the scoping issues that plagued the older 'var' keyword. You use 'let' when you know the variable's value will need to change later in the program (like a counter in a loop or a toggle state).
Syntax
'let' is scoped to the nearest enclosing block (denoted by {}). It does not leak out of loops or if-statements like 'var' does.
Block Scoping with let
javascript
let count = 0;
if (true) {
let count = 5; // This is a different 'count'
console.log(count); // 5
}
console.log(count); // 0Common Pitfalls
- Trying to re-declare the same variable with 'let' in the same scope throws a SyntaxError.
Interview Tips
- Explain the difference between block scope (let, const) and function scope (var).
Real-World Example
Using let in a for-loop prevents variables from leaking into the global scope.
example
javascript
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Output: 0, 1, 2. (If this was 'var', it would output 3, 3, 3)