let

Declares a block-scoped variable whose value you can change later.

On this page

Example

#
JavaScript
let level = 1
let points = 0

points += 120
if (points >= 100) {
  level = 2
}

console.log(level, points)
Console
2 120

Definition and usage

#

The let keyword creates a variable whose value you can overwrite while the program runs. It’s a good fit for counters, totals, flags, and anything that changes step by step.

A variable declared with let only lives inside the block where you declared it, meaning between the nearest curly braces { }. Outside an if block, a loop, or a function, it simply doesn’t exist, so you won’t accidentally overwrite a variable with the same name from another part of the code.

You can’t use a variable before the line that declares it. This stretch of code is called the temporal dead zone (TDZ), and trying to read it there throws a ReferenceError. You also can’t declare a variable with the same name twice in the same block.

Syntax

#
Syntax
let name
let name = value
let name1 = value1, name2 = value2

More examples

#
Block scope
JavaScript
let message = 'outside the block'

if (true) {
  let message = 'inside the block'
  console.log(message)
}

console.log(message)
Console
inside the block
outside the block
Temporal dead zone (TDZ)
JavaScript
try {
  console.log(score)
} catch (error) {
  console.log(error.name)
}

let score = 50
console.log(score)
Console
ReferenceError
50
Each loop turn gets its own variable
JavaScript
const callbacks = []

for (let i = 0; i < 3; i++) {
  callbacks.push(() => i)
}

console.log(callbacks.map((callback) => callback()))
Console
[0, 1, 2]

If the counter were declared with var, all the functions would share one variable and would return 3.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Start with const. Switch to let only once a variable really needs to receive a new value, for example as a counter or a running total.
  • Declare a variable as close as possible to where you use it. The smaller the scope, the fewer places where something can overwrite it.
  • To change a value, just write the assignment itself, points = 10. Writing let points again in the same block is a syntax error.

Related entries

#

Spotted a mistake or missing an example? Write to us.