JavaScript let Keyword: A Complete Tutorial with Examples

The let keyword in JavaScript is used to declare variables that can be reassigned later.

Introduced in ES6 (ECMAScript 2015), let is block-scoped, which means it is confined to the block (usually denoted by {}) in which it is declared.

This makes it different from the older var keyword, which is function-scoped.

Why Use let?

Block Scope: let limits the variable’s scope to the block, statement, or expression where it is used.
No Hoisting Issue: Unlike var, let is not hoisted to the top of the block, preventing undefined errors.
Reassignment: Variables declared with let can be reassigned new values.

Syntax

let variableName = value;

variableName: The name of the variable you want to create.
value (optional): The initial value you want to assign to the variable.

Examples

1. Basic Usage of let

let age = 25;
console.log(age); // Output: 25

age = 30; // Reassigning the value
console.log(age); // Output: 30

Explanation

let age = 25; declares a variable named age and assigns it the value 25.
The value of age is then reassigned to 30.

2. Block Scope with let

One of the key differences between let and var is that let is block-scoped. This means a variable declared with let is only accessible within the block in which it is declared.

if (true) {
  let message = 'Hello, World!';
  console.log(message); // Output: "Hello, World!"
}

console.log(message); // Error: message is not defined

Explanation

message is declared inside the if block using let.
Trying to access message outside the block results in an error because let confines it to the block scope.

3. Difference Between var and let

var is function-scoped, while let is block-scoped. Here’s an example to highlight the difference.

function testVar() {
  if (true) {
    var x = 5;
  }
  console.log(x); // Output: 5 (var is function-scoped)
}

function testLet() {
  if (true) {
    let y = 10;
  }
  console.log(y); // Error: y is not defined (let is block-scoped)
}

testVar();
testLet();

Explanation

In testVar(), x is accessible outside the if block because var is function-scoped.
In testLet(), y is not accessible outside the if block because let is block-scoped.

4. Temporal Dead Zone with let

Variables declared with let are in a “temporal dead zone” from the start of the block until the declaration is encountered. This means you cannot use a let variable before it is declared.

console.log(name); // Error: Cannot access 'name' before initialization
let name = 'Alice';

Explanation

Trying to access name before it is declared with let results in an error.
This behavior is different from var, which would print undefined in a similar situation due to hoisting.

5. Re-declaring Variables with let

Unlike var, you cannot re-declare the same variable in the same scope using let.

let count = 1;
let count = 2; // Error: Identifier 'count' has already been declared

Explanation

Attempting to declare count twice with let in the same scope results in an error.
This helps prevent accidental re-declarations that might lead to bugs.

6. Using let in Loops

When used in loops, let creates a new scope for each iteration, making it safer and more predictable than using var.

for (let i = 0; i < 3; i++) { setTimeout(() => {
    console.log(i); // Output: 0, 1, 2
  }, 1000);
}

Explanation

Each iteration of the for loop creates a new scope for i when using let.
This results in the correct values (0, 1, 2) being logged, unlike when using var, which would log 3 for all iterations due to its function scope.

7. let in Nested Blocks

let variables can be confined to nested blocks, which allows for more control over variable scoping.

let outer = 'I am outside!';

if (true) {
  let inner = 'I am inside!';
  console.log(outer); // Output: "I am outside!"
  console.log(inner); // Output: "I am inside!"
}

console.log(inner); // Error: inner is not defined

Explanation

inner is declared inside the if block using let, so it is not accessible outside of that block.
outer is accessible inside the block since it was declared in the outer scope.

8. Avoiding var-related Bugs Using let

Here’s a common bug that occurs when using var inside a loop and how let solves it.

Using var

for (var i = 0; i < 3; i++) { setTimeout(() => {
    console.log(i); // Output: 3, 3, 3
  }, 1000);
}

Using let

for (let i = 0; i < 3; i++) { setTimeout(() => {
    console.log(i); // Output: 0, 1, 2
  }, 1000);
}

Explanation

When using var, the loop variable i is function-scoped, causing it to retain its final value (3) in each iteration of the setTimeout callbacks.
When using let, the loop variable i is block-scoped, creating a new i for each iteration, thus logging 0, 1, and 2.

Summary

The let keyword offers a more controlled and predictable way to declare variables in JavaScript due to its block-scoping and avoidance of hoisting issues. It is preferred over var in most modern JavaScript codebases.

Key Points

Block Scope: let variables are confined to the block where they are declared.
No Hoisting Issues: Unlike var, let variables cannot be accessed before their declaration.
Reassignment: Variables declared with let can be reassigned.
Cannot Re-declare in the Same Scope: Prevents accidental re-declaration of variables.
Ideal for Loops: Provides correct scoping in loops, avoiding common pitfalls associated with var.

By understanding and using let, you can write more reliable and bug-free JavaScript code.

Remember to use let for variables that may need to change their values and block scope behavior.

Related posts

JavaScript Operator Precedence

JavaScript Reserved Keywords

JavaScript Syntax Tutorial with Examples