const

Declares a block-scoped constant. A variable like this can’t be assigned a new value.

On this page

Example

#
JavaScript
const courseName = 'JavaScript Fundamentals'
const maxPoints = 100

try {
  maxPoints = 200
} catch (error) {
  console.log(error.name)
}

console.log(courseName, maxPoints)
Console
TypeError
JavaScript Fundamentals 100

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

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

More examples

#
The contents of an object or array can still change
JavaScript
const student = { name: 'Emma', points: 120 }
student.points += 30

const tasks = ['HTML']
tasks.push('CSS')

console.log(student)
console.log(tasks)
Console
{ name: 'Emma', points: 150 }
['HTML', 'CSS']
Full protection with Object.freeze()
JavaScript
const settings = Object.freeze({ theme: 'dark', sounds: true })

try {
  settings.theme = 'light'
} catch (error) {
  console.log(error.name)
}

console.log(settings.theme)
Console
TypeError
dark

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 in a for...of loop
JavaScript
const lessons = ['Variables', 'Loops', 'Functions']

for (const lesson of lessons) {
  console.log(lesson.toUpperCase())
}
Console
VARIABLES
LOOPS
FUNCTIONS

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 const by default. Switch to let only once a variable actually needs to receive a new value.
  • const doesn’t make a copy or protect the contents. If an object needs to stay untouched, freeze it with Object.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

#

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