In multi-line expressions, you can store and update intermediate values using variables.
Variable Declaration
- Bare assignment (
name = value): Sets a variable. If the variable doesn't exist, it is created in the current scope. If it exists in an outer scope, it updates that existing variable. - Declaration (
let name = value): Explicitly creates a new variable in the current scope. - Constant declaration (
const name = value): Creates a new variable that cannot be reassigned.
Scopes and Shadowing
Scopes are defined by blocks { ... } (e.g., inside if, for, while, or functions).
- Shadowing: Using
let or const inside a block creates a new variable that hides any outer variable with the same name within that block. - Persistence: To make a value survive a block (like a loop or
if statement), declare it before the block using let or const, then update it inside using a bare assignment.
Rule of thumb: Use let/const for fresh variables; use bare assignment name = ... to update existing variables in outer scopes (like accumulators).
// Updating an outer variable (Accumulator pattern)
let total = 0
for (const x of [1, 2, 3]) {
total = total + x // updates the outer `total`
}
total // 6
// Shadowing (Inner variable hides outer)
let name = 'outer'
if (true) {
let name = 'inner' // a separate variable
name // 'inner' here
}
name // still 'outer'