let
Declares a block-scoped variable whose value you can change later.
Example
#let level = 1
let points = 0
points += 120
if (points >= 100) {
level = 2
}
console.log(level, points)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
#let name
let name = value
let name1 = value1, name2 = value2More examples
#let message = 'outside the block'
if (true) {
let message = 'inside the block'
console.log(message)
}
console.log(message)try {
console.log(score)
} catch (error) {
console.log(error.name)
}
let score = 50
console.log(score)const callbacks = []
for (let i = 0; i < 3; i++) {
callbacks.push(() => i)
}
console.log(callbacks.map((callback) => callback()))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 toletonly 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. Writinglet pointsagain in the same block is a syntax error.
Related entries
#- let vs const vs varconst and let have block scope, while var has function scope. const doesn’t allow reassignment. In new code write const, and let only for values that change.
- constDeclares a block-scoped constant. A variable like this can’t be assigned a new value.
- varDeclares a function-scoped variable. This is the older way, replaced today by let and const.
- if...elseRuns a block of code only when the condition is true, and otherwise an optional else block.
- forA loop with a counter: initialization, condition, and step. Repeats a block of code while the condition is true.
Spotted a mistake or missing an example? Write to us.