JavaScript Let
The let
keyword is used to declare variables in JavaScript. Variables declared with let
are block-scoped, meaning they are only accessible within the block, statement, or expression in which they are defined. Unlike var
, let
does not allow variables to be redeclared within the same scope.
Key Topics
Block Scope
Variables declared with let
are only accessible within the block in which they are defined.
{
let x = 10;
console.log(x); // Inside the block
}
console.log(typeof x); // Outside the block
Output
> 10
> undefined
Redeclaring Variables
Variables declared with let
cannot be redeclared within the same scope, ensuring a safer programming experience.
let x = 5;
// let x = 10; // Error: Identifier 'x' has already been declared
x = 10; // Allowed: Updating the value
console.log(x);
Output
> 10
Temporal Dead Zone
Variables declared with let
are in a "temporal dead zone" from the start of the block until the declaration is encountered. This prevents access before the declaration.
console.log(a); // Error: Cannot access 'a' before initialization
let a = 20;
console.log(a);
Output
> ReferenceError: Cannot access 'a' before initialization
> 20
Examples of Using Let
Below is a practical example of using let
in a function and a loop.
function countNumbers() {
for (let i = 0; i < 3; i++) {
console.log(i);
}
// console.log(i); // Error: i is not defined outside the loop
}
countNumbers();
Output
> 0
> 1
> 2
Key Takeaways
- Block Scope:
let
variables are limited to the block in which they are declared. - Redeclaration:
let
prevents redeclaring variables in the same scope. - Temporal Dead Zone: Ensures variables cannot be used before they are declared.
- Best Practice: Use
let
for variables that may change within their scope.