const
Declares a block-scoped constant. A variable like this can’t be assigned a new value.
Example
#const courseName = 'JavaScript Fundamentals'
const maxPoints = 100
try {
maxPoints = 200
} catch (error) {
console.log(error.name)
}
console.log(courseName, maxPoints)Definition and usage
#const creates a variable that can’t be reassigned. You give it a value right at declaration, and any later attempt to use =, +=, or ++ on that name throws a TypeError.
A constant blocks the assignment itself, not the contents. If it holds an object or an array, you can still add elements, remove them, and change fields. You just can’t swap the whole value for a different one.
The scope works the same as with let: a block in curly braces, with a temporal dead zone before the declaration. In modern code, const is the default choice, because it’s immediately clear that the name points to the same value the whole time.
Syntax
#const name = value
const name1 = value1, name2 = value2More examples
#const student = { name: 'Emma', points: 120 }
student.points += 30
const tasks = ['HTML']
tasks.push('CSS')
console.log(student)
console.log(tasks)const settings = Object.freeze({ theme: 'dark', sounds: true })
try {
settings.theme = 'light'
} catch (error) {
console.log(error.name)
}
console.log(settings.theme)The examples run as a module, meaning in strict mode, so writing to a frozen object throws a TypeError. Outside strict mode, the change would be silently ignored.
const lessons = ['Variables', 'Loops', 'Functions']
for (const lesson of lessons) {
console.log(lesson.toUpperCase())
}In for...of, each turn creates a new constant, so const works fine. In a classic for (let i = 0; ...) you need let, because the counter changes.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Write
constby default. Switch toletonly once a variable actually needs to receive a new value. constdoesn’t make a copy or protect the contents. If an object needs to stay untouched, freeze it withObject.freeze(), or create new objects with spread.- Configuration constants known up front are often written in capital letters, e.g.
MAX_FUEL. That’s just a convention, the language doesn’t require it.
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.
- letDeclares a block-scoped variable whose value you can change later.
- varDeclares a function-scoped variable. This is the older way, replaced today by let and const.
- Object.freeze()Freezes an object, blocking the addition, removal, and change of its properties.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
Spotted a mistake or missing an example? Write to us.