Lesson 8 +10 XP

JavaScript Const

JavaScript Const

The const keyword declares a constant: a value that cannot be reassigned.

Declaring a constant

const pi = 3.14159;

What you cannot do

const pi = 3.14;
pi = 3.15;        // Error: can't reassign a constant
const pi = 3.16;  // Error: can't redeclare

Must have a value

A const variable must be assigned a value when declared:

const x; // Error: missing initializer

const does not mean immutable

const only prevents reassignment. You can still change the contents of arrays and objects declared with const:

const colors = ["red", "green"];
colors.push("blue"); // OK, contents change
colors = [];         // Error: reassignment not allowed

When to use const

Use const by default. If you know a variable must change later, use let. This makes your intent clear.

const is block scoped

Like let, const is block scoped.

TL;DR

  • const values cannot be reassigned.
  • A const must be initialized when declared.
  • You can still change object/array contents.
  • Use const by default, let only when needed.