let & const
Learn how to declare variables in modern JavaScript using the two keywords that replaced var: choosing the right one makes your code safer and easier to read.
What Is a Variable?
A variable is a named container that stores a value in your program's memory. Think of it as a labelled box: the label is the variable's name, and what you put inside is its value.
Declaring with let
Use let when you need a variable whose value will change later in your program. You can reassign it as many times as you like.
score = score + 10; // now 10 ✓
score = 25; // now 25 ✓
Declaring with const
Use const when a variable should never be reassigned after its initial value. The engine will throw an error if you try.
const greeting = "Hello!";
TAX_RATE = 0.10; // TypeError! ✕
The Golden Rule
Block Scope Explained
Both let and const are block-scoped: they only exist inside the nearest pair of curly braces { } where they are declared.
let vs const vs var
Hoisting & the Temporal Dead Zone
Variables declared with let and const are hoisted to the top of their block, but they are not initialized. Accessing them before the declaration line causes a ReferenceError. This gap is called the Temporal Dead Zone (TDZ).
How to Choose the Right Keyword
Example 1: Counting Loop
let count = 0;
for (let i = 0; i < fruits.length; i++) {
count += 1;
}
console.log(count); // 3
Example 2: const with Objects
user.age = 18; // ✓ mutating a property
user.email = "ada@x.co"; // ✓ adding a property
user = { name: "Bob" }; // ✕ TypeError!
Example 3: Real-World Pattern
const MAX_RETRIES = 3;
let attempts = 0;
let success = false;
while (!success && attempts < MAX_RETRIES) {
attempts += 1;
success = tryFetch(API_URL);
}
const ≠ Immutable
Common Mistakes
Summary Comparison
| Feature | let | const | var |
|---|---|---|---|
| Scope | Block | Block | Function |
| Reassignable | Yes | No | Yes |
| Redeclarable | No | No | Yes |
| Hoisted | TDZ | TDZ | undefined |
| Must initialize | No | Yes | No |
Question 1 of 5
Which keyword should you use for a variable that never needs to be reassigned?
Question 2 of 5
What happens when you run this code?
const x = 10; x = 20;
Question 3 of 5
const arr = [1, 2, 3]; arr.push(4);
Does this code throw an error?
Question 4 of 5
What is the scope of variables declared with let and const?
Question 5 of 5
What does the Temporal Dead Zone (TDZ) refer to?