In JavaScript, the `const` keyword is often misunderstood, particularly when it comes to objects and their properties. While `const` does prevent the reassignment of the variable itself, it does not make the object immutable. This means that while you cannot assign a new object to a `const` variable, you can still modify the properties of the object that the variable points to. Understanding this behavior is crucial for effective JavaScript programming.
The `const` keyword is used to declare variables that are block-scoped and cannot be reassigned. However, it is important to note that `const` applies to the variable binding, not the value itself. This distinction is particularly important when dealing with objects and arrays.
const person = {
name: "John",
age: 30
};
// Modifying properties
person.age = 31; // This is allowed
person.name = "Jane"; // This is also allowed
// Reassigning the object itself will throw an error
// person = { name: "Doe", age: 25 }; // Uncaught TypeError: Assignment to constant variable.
In the example above, we declare a `const` object named `person`. We can change the properties `name` and `age` without any issues. However, if we try to reassign `person` to a new object, we encounter a TypeError.
const person = Object.freeze({
name: "John",
age: 30
});
// Attempting to modify properties will fail silently in non-strict mode
person.age = 31; // This will not change the age property
console.log(person.age); // Outputs: 30
// In strict mode, it will throw an error
"use strict";
const personStrict = Object.freeze({
name: "John",
age: 30
});
personStrict.age = 31; // Uncaught TypeError: Cannot assign to read only property 'age' of object '#
In summary, while `const` prevents reassignment of the variable itself, it does not prevent modification of the properties of an object. Understanding this behavior is essential for writing robust JavaScript code. By following best practices and being aware of common pitfalls, developers can effectively manage object properties and maintain clean, error-free code.