In JavaScript, the let
keyword is used to declare variables with block scope. Block scope means that the variable is only accessible within the block of code where it is declared. This is in contrast to the var
keyword, which has function scope. Here are some ways you can use let
in JavaScript:
Variable Declaration:
javascriptlet x; // Declaring a variable named 'x'
Variable Initialization:
javascriptlet y = 10; // Declaring and initializing a variable named 'y' with the value 10
Block Scope:
javascriptif (true) {
let z = 5;
console.log(z); // z is accessible within this block
}
// console.log(z); // This would result in an error because z is not defined in this scope
For Loops:
javascriptfor (let i = 0; i < 5; i++) {
// i is only accessible within this loop
console.log(i);
}
// console.log(i); // This would result in an error because i is not defined in this scope
Re-declaration in the Same Scope:
javascriptlet a = 3;
// let a = 5; // This would result in an error because a is already declared in this scope
Shadowing:
javascriptlet b = 10;
if (true) {
let b = 5; // This 'b' shadows the outer 'b' within this block
console.log(b); // Outputs 5
}
console.log(b); // Outputs 10, the outer 'b' is not affected by the inner one
Temporal Dead Zone (TDZ):
javascript// console.log(tempVar); // This would result in a ReferenceError
let tempVar = 20; // The variable is declared but not yet initialized, it's in the TDZ until this line
console.log(tempVar); // Outputs 20
These are some common use cases for let
in JavaScript. It's important to note that let
has block scope, so variables declared with it are limited in their visibility to the block in which they are defined.