Back to course

Variables 103: The 'const' Keyword (Immutability)

JavaScript: The Complete '0 to Hero' Beginner Course

9. Variables: The const Keyword

const (short for constant) is used for variables whose value should never change after initialization. It also uses block scope like let.

Declaration and Initialization

const variables must be initialized when they are declared.

javascript const PI = 3.14159; const COMPANY_NAME = 'Tech Corp';

// const taxRate; // ERROR: Missing initializer in const declaration

Immutability (Read-Only)

Once assigned, a const variable cannot be reassigned.

javascript const MAX_ATTEMPTS = 3;

// MAX_ATTEMPTS = 4; // ERROR: TypeError: Assignment to constant variable

Const vs. Mutability (Important Caveat)

While you cannot reassign a const variable, if the variable holds an Object or Array (non-primitive types, covered later), you can still modify the contents of that object or array.

javascript const myArr = [1, 2, 3]; myArr.push(4); // OK: We changed the content, not the variable binding itself. console.log(myArr); // [1, 2, 3, 4]

Rule of Thumb: Use const by default. Only switch to let if you absolutely need to reassign the variable.