ArticleZip > Why Can I Change A Constant Object In Javascript

Why Can I Change A Constant Object In Javascript

Have you ever wondered why you can change a constant object in JavaScript? Well, let's dive into this interesting aspect of JavaScript programming! Constants are defined using the `const` keyword in JavaScript. When you declare a constant object using `const`, you might think that the object is immutable and cannot be modified. However, the behavior of constant objects in JavaScript can sometimes be a little surprising.

In JavaScript, the `const` keyword is used to declare constants. When you declare a constant object using `const`, you are actually creating a constant reference to an object. This means that while the reference itself cannot be reassigned to point to a different object, the properties of the object can still be modified.

For example, consider the following code snippet:

Javascript

const person = { name: "Alice" };
person.name = "Bob";
console.log(person.name); // Output: "Bob"

In this code snippet, we declared a constant object `person` with a `name` property initially set to "Alice". Even though `person` is a constant, we can still modify the `name` property of the object. When we log the `person.name` to the console after changing it to "Bob", we see that the output is indeed "Bob".

So, why does this happen? The behavior is because the `const` declaration only prevents the variable itself from being reassigned to a different value or object. It does not make the object immutable. If you need to ensure that an object is truly immutable, you can use other techniques such as Object.freeze or libraries like Immutable.js.

If you want to prevent the modification of properties in a constant object, you can use `Object.freeze` to make the object immutable. Here's an example:

Javascript

const frozenPerson = Object.freeze({ name: "Alice" });
frozenPerson.name = "Bob"; // This will throw an error in strict mode
console.log(frozenPerson.name); // Output: "Alice"

In this modified example, we are using `Object.freeze` to create an immutable object `frozenPerson`. When we try to modify the `name` property of the frozenPerson object, JavaScript will throw an error in strict mode, preventing the property from being changed.

In conclusion, the ability to change the properties of a constant object in JavaScript is due to the nature of how `const` works with objects. Remember that `const` creates a constant reference and not a truly immutable object. If you need immutability, consider using `Object.freeze` or other techniques to ensure that your objects remain unchanged. Stay curious and keep exploring the fascinating world of JavaScript programming!

×