JavaScript let
letwas introduced in ES6 (2015) as a modern way to declare variables- Variables declared with let are block-scoped
- A let variable can be reassigned but not redeclared in the same scope
- let variables are not attached to the window object
- let helps prevent the accidental bugs common with var
- It is the recommended choice for values that will change
What Is let in JavaScript?
The let keyword lets you declare a variable whose value you expect to change later, such as a counter, a running total, or user input that gets updated. It was added to JavaScript to fix some of the confusing behaviour of var, mainly by respecting block scope properly.
Basic Example of let
<script>
let score = 10;
score = 15;
console.log(score);
</script>
Block Scope Explained
Unlike var, a variable declared with let inside an if block or a for loop stays inside that block and cannot be accessed outside of it. This matches how most beginners naturally expect variables to behave, which is one reason let feels more predictable than var. If you try to use a let variable outside the block where it was created, JavaScript will throw an error instead of silently allowing it.
Key Characteristics of let
Block-Scoped
Only exists inside the nearest set of curly braces where it was declared.
Reassignable
The value can be changed as many times as needed after declaration.
No Redeclaration
Declaring the same let variable twice in one scope causes an error.
Temporal Dead Zone
A let variable cannot be used before its declaration line runs.
let in a Loop
One of the most practical benefits of let shows up inside loops. Each pass through a loop gets its own separate copy of a let variable, which avoids a classic bug where every function created inside a loop ends up sharing the same final value. This makes let especially useful when writing loops that create functions, timers, or event listeners.
When to Use let
Use let whenever you know a variable's value will need to change after it is first set, such as a counter that increases, a flag that switches between true and false, or a value updated based on user interaction. If a value should never change once assigned, const is usually the better and safer choice, which is covered next.