A constant in JavaScript is a variable that cannot be reassigned after its initialization.
This means that once a value has been assigned to a constant, we cannot change it during the program’s execution. This prevents potential mistakes and improves code maintainability.
In JavaScript, constants are declared using the const keyword, which was introduced in ECMAScript 6 (2015).
If you want to learn more, check out the Introduction to Programming Course
Declaring constants
The basic syntax for declaring a constant in JavaScript is as follows:
const CONSTANT_NAME = value;
For example,
const PI = 3.14159;
const API_URL = "https://api.example.com/data";
In these examples,
PIandAPI_URLare constants- Attempting to reassign a new value to these constants will generate an error
Using constants with primitive types
Constants can be used with any primitive type in JavaScript (such as numbers, strings, booleans).
const MAX_USERS = 100;
const WELCOME_MESSAGE = "Welcome to the JavaScript course";
const IS_ADMIN = true;
Using constants with objects and Arrays
Although its name is misleading, constant should not be confused with immutable. const guarantees that a variable’s value cannot be changed after its assignment.
However, if the variable is a reference (like an object or an array), the properties or elements of that object or array can be modified.
Let’s see it with an example,
const user = {
name: "Luis",
age: 30
};
// Trying to reassign the object
user = { name: "María", age: 25 }; // This will generate an error
// Modifying a property
user.age = 31; // This is valid
In the example,
- We CANNOT reassign the
userobject because it is constant - But NOTHING PREVENTS us from modifying its members.
Similarly, with an array
const numbers = [1, 2, 3, 4, 5];
// Trying to reassign the array
numbers = [10, 20, 30]; // This will generate an error
// Modifying an element
numbers[0] = 10; // This is valid
// Adding a new element
numbers.push(6); // This is valid
- We CANNOT reassign the
numbersobject - But NOTHING PREVENTS us from modifying its elements
If you want to learn more, check out the Introduction to Programming Course
Constants in block context
Constants, like variables declared with let, have block scope. This means a constant is only available within the block where it is declared.
if (true) {
const MESSAGE = "Hello World";
console.log(MESSAGE); // "Hello World"
}
console.log(MESSAGE); // Error: MESSAGE is not defined
Furthermore, they are also subject to the TDZ (Temporal Dead Zone). This means they cannot be accessed before their declaration in the code.
console.log(GREETING); // Error: Cannot access 'GREETING' before initialization
const GREETING = "Hello";
