The `let` keyword in JavaScript is used to declare variables that are block-scoped. Unlike `var`, which declares variables globally or locally to an entire function regardless of block scope, `let` confines the variable's scope to the block, statement, or expression it's used in.
Example 1: Basic Usage
let name = "Alice";
console.log(name); // Output: Alice
name = "Bob";
console.log(name); // Output: Bob
In this example, a variable `name` is declared and initialized with the value "Alice". The value is then changed to "Bob". Both values are printed to the console.
Example 2: Block Scope
if (true) {
let age = 25;
console.log(age); // Output: 25
}
console.log(age); // Error: age is not defined
Here, the variable `age` is declared inside an `if` block using `let`. It is accessible within that block but not outside of it. Trying to access `age` outside the block results in an error.
Example 3: Loop Scope
for (let i = 0; i < 3; i++) {
console.log(i); // Output: 0, 1, 2
}
console.log(i); // Error: i is not defined
In this loop, `i` is declared with `let`. It is only accessible within the loop. Trying to access `i` outside the loop causes an error.
Example 4: Avoiding Variable Hoisting Issues
console.log(a); // Error: Cannot access 'a' before initialization
let a = 10;
With `var`, you can access the variable before it is declared (though it will be `undefined`), but with `let`, accessing the variable before it is declared will throw a `ReferenceError`.
Example 5: No Re-declaration within the Same Scope
let x = 10;
let x = 20; // Error: Identifier 'x' has already been declared
Re-declaring a variable in the same scope with `let` results in an error, unlike `var`, which allows re-declaration in the same scope.
Example 6: `let` in Nested Blocks
let number = 5;
if (true) {
let number = 10;
console.log(number); // Output: 10
}
console.log(number); // Output: 5
In this example, the outer `let` declaration of `number` is separate from the inner `let` declaration inside the `if` block. The inner block has its own scope and does not affect the outer variable.
Example 7: Temporal Dead Zone
{
console.log(temp); // Error: Cannot access 'temp' before initialization
let temp = "hello";
console.log(temp); // Output: hello
}
The temporal dead zone is the time between entering the scope and the variable being declared. In this period, the variable cannot be accessed. Attempting to do so results in a `ReferenceError`.
Using `let` helps in writing cleaner, more predictable code by avoiding many of the pitfalls associated with `var`, such as hoisting and scope leakage.