Learn how to declare constants in JavaScript using the `const` keyword, understand their immutability, and explore common misconceptions.
const
In JavaScript, the const
keyword is used to declare variables that are meant to remain constant throughout the execution of a program. Understanding how to effectively use const
is crucial for writing robust and maintainable code. In this section, we will explore the syntax and purpose of const
, discuss the immutability of bindings, and clarify common misconceptions.
const
The const
keyword in JavaScript is used to create a variable that cannot be reassigned. This means once a value is assigned to a const
variable, it cannot be changed through reassignment. This characteristic makes const
particularly useful for defining constants—values that should remain unchanged throughout the program.
const
The syntax for declaring a constant using const
is straightforward. Here’s how you can declare a constant:
const PI = 3.14159;
In this example, PI
is a constant representing the mathematical constant π (pi). Once declared, PI
cannot be reassigned to a different value.
A common point of confusion when using const
is the distinction between the immutability of the binding and the mutability of object properties. Let’s break this down:
Immutability of Bindings: When you declare a variable with const
, the binding itself is immutable. This means you cannot reassign the variable to a different value or object.
Mutability of Object Properties: If the constant is an object (including arrays), the properties or elements of that object can still be changed. The immutability of const
only applies to the binding, not the contents of the object.
const number = 42;
number = 50; // Error: Assignment to constant variable.
In this example, attempting to reassign number
results in an error because number
is a constant.
const person = {
name: 'Alice',
age: 30
};
// Modifying a property of the object
person.age = 31; // This is allowed
// Attempting to reassign the object
person = { name: 'Bob', age: 25 }; // Error: Assignment to constant variable.
Here, while we cannot reassign the person
object to a new object, we can modify its properties.
const
const
Makes Objects ImmutableA common misconception is that declaring an object with const
makes the object itself immutable. As we’ve seen, this is not true. The object’s properties can still be changed.
const
Variables Must Be Initialized ImmediatelyUnlike let
and var
, const
variables must be initialized at the time of declaration. This requirement ensures that the constant is assigned a value before it is used.
const greeting; // Error: Missing initializer in const declaration
const
const
for values that should not change, such as mathematical constants or configuration values.const MAX_USERS = 100;
const API_URL = 'https://api.example.com';
const
when you want to ensure that a variable reference does not change, even if the object it points to might.const settings = {
theme: 'dark',
notifications: true
};
const
Variable: Attempting to reassign a const
variable will result in an error.const color = 'blue';
color = 'red'; // Error: Assignment to constant variable.
const
variables must be initialized when they are declared.const user; // Error: Missing initializer in const declaration
Let’s look at some practical examples to solidify our understanding of const
.
const
for Constantsconst TAX_RATE = 0.07;
function calculateTotal(price) {
return price + (price * TAX_RATE);
}
console.log(calculateTotal(100)); // Outputs: 107
In this example, TAX_RATE
is a constant that represents a fixed tax rate. It is used in the calculateTotal
function to compute the total price including tax.
const
with Objectsconst car = {
make: 'Toyota',
model: 'Corolla'
};
// Modifying properties
car.model = 'Camry'; // Allowed
// Reassigning the object
car = { make: 'Honda', model: 'Civic' }; // Error: Assignment to constant variable.
Here, we can change the model
property of the car
object, but we cannot reassign car
to a new object.
const
BehaviorTo better understand how const
works, let’s visualize the concept of immutability of bindings and mutability of object properties using a diagram.
graph TD; A[const myObject] --> B{Binding Immutability} A --> C{Object Mutability} B --> D[Cannot Reassign myObject] C --> E[Can Change Properties]
Diagram Description: This diagram illustrates that a const
binding is immutable, meaning the variable cannot be reassigned. However, if the const
variable is an object, its properties can still be changed.
Experiment with the following code examples to deepen your understanding of const
. Try modifying the properties of objects declared with const
and observe the behavior.
const fruits = ['apple', 'banana', 'cherry'];
// Add a new fruit
fruits.push('date'); // Allowed
// Reassign the array
fruits = ['kiwi', 'mango']; // Error: Assignment to constant variable.
Challenge: Modify the fruits
array by adding or removing elements without reassigning the array itself.
For more information about const
and variable declarations in JavaScript, consider exploring the following resources:
Before moving on, let’s summarize the key points:
const
is used to declare variables that cannot be reassigned.const
applies to the binding, not the object properties.const
variables must be initialized at the time of declaration.const
for values that should remain constant throughout the program.Remember, mastering JavaScript is a journey, and understanding the nuances of const
is a significant step forward. Keep experimenting, stay curious, and enjoy the process of learning and discovery.