JS Const
In this page:
const CONSTANT_NAME = value;
Constant Values
A const variable's binding is locked in place the moment it's declared, meaning you can never point that same variable name at a different value later in the script.
Example: Constant Values
const maxUsers = 100;
// maxUsers = 200; // TypeError: Assignment to constant variable
console.log(maxUsers);
const Must Be Initialized
Because a const variable's value can never change after declaration, JavaScript requires you to provide that value immediately, declaring a const without one is not allowed.
Example: const Must Be Initialized
const pi = 3.14159;
// const withoutValue; // SyntaxError: Missing initializer in const declaration
console.log(pi);
const With Objects
When a const variable holds an object, the variable itself cannot be reassigned to a new object, but the properties inside that object can still be freely added, changed, or removed.
Example: const With Objects
const user = { name: "Amit" };
user.name = "Priya"; // allowed, modifying a property
// user = {}; // TypeError, cannot reassign the variable
console.log(user);
const With Arrays
The same rule applies to arrays declared with const, the array's elements can be added, removed, or changed using array methods, but the variable can never be reassigned to point at a completely different array.
Example: const With Arrays
const numbers = [1, 2, 3];
numbers.push(4); // allowed
// numbers = []; // TypeError, cannot reassign
console.log(numbers);
When to Use const
const should be the default choice for the vast majority of variables in modern JavaScript, using it consistently signals to anyone reading the code exactly which values are meant to stay fixed and which, marked with let, are expected to change.
Example: When to Use const
const taxRate = 0.08; // never changes
let price = 100;
console.log(price + price * taxRate);
- Trying to reassign a const variable directly, which always throws a TypeError, regardless of the value's type.
- Assuming const makes an object or array completely unchangeable, when only the variable's binding is actually protected.
- Declaring a const without immediately giving it a value, which is not allowed since const requires initialization at declaration.
- const creates a variable whose binding cannot be reassigned after it's declared.
- const requires a value at the moment of declaration, unlike let which can be declared without one.
- Objects and arrays declared with const can still have their internal contents modified, only reassignment of the variable itself is blocked.
const has been supported in every major browser since 2015 and is considered a fully standard, safe part of modern JavaScript.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: