Home >Web Front-end >JS Tutorial >How Do JavaScript Constants Work with Objects and Arrays?
Understanding Constant Objects in JavaScript: A Comprehensive Guide
Constants, introduced in ES6, provide a way to prevent the reassignment and redeclaration of variables. However, the concept of constants in JavaScript can be confusing, especially when it comes to objects.
The Nature of Constants
According to the specification, "The value of a constant cannot change through re-assignment, and a constant cannot be re-declared." This means that once a constant is declared, its value cannot be directly modified or its identity changed.
Arrays and Objects Exception
However, when dealing with arrays and objects, a subtle distinction arises. When adding items to an array or properties to an object, you are not re-assigning or re-declaring the constant. Instead, you are modifying the internal state of the existing object.
Practical Examples
Consider this code:
const xxx = 6; xxx = 999; // Error xxx++; // Error const yyy = []; yyy = 'string'; // Error yyy = [15, 'a']; // OK yyy.push(6); // OK yyy.push(1); // OK
In the case of xxx, both attempts to re-assign its value result in errors. However, for yyy, the push() method successfully adds elements to the array. This is because the push() method modifies the array in place without re-assigning its identity.
Conclusion
Constants in JavaScript serve as powerful tools for preventing unintended changes to variables. However, it is important to understand that constants do not completely freeze objects. While the identity and assigned value of the constant object cannot be altered, its internal state (such as the elements of an array or the properties of an object) can be modified without violating the rules of const.
The above is the detailed content of How Do JavaScript Constants Work with Objects and Arrays?. For more information, please follow other related articles on the PHP Chinese website!