Ionică Bizău
Ionică Bizău

Reputation: 113365

Why are the constant fields un-protected?

const can be used to declare constants:

> const a = 42
undefined
> a = 7
7
> a
42

This is cool, but I observed that when using const to declare objects this behavior doesn't work anymore:

> const b = { foo: { bar: 42 }, baz: 7 }
undefined
> b.baz = { hello: "world" }
{ hello: 'world' }
> b.foo.bar = 7
7
> b
{ foo: { bar: 7 }, baz: { hello: 'world' } }

As you can see, I modified the baz field into an object and I changed 42 into 7.

Reading the docs I see this is expected:

// Overwriting the object fails as above (in Firefox and Chrome
but not in Safari)
MY_OBJECT = {"OTHER_KEY": "value"};

// However, object attributes are not protected,
// so the following statement is executed without problems
MY_OBJECT.key = "otherValue";

However, why this is working like this? What is the logic behind?

On the other side, the question would be: how to declare constant objects?

Upvotes: 1

Views: 43

Answers (1)

Bergi
Bergi

Reputation: 664538

However, why this is working like this? What is the logic behind?

const is only declaring a binding as constant. It doesn't automatically make every value that it is initialised with immutable.

how to declare constant objects?

To prevent an object from being mutated, you can Object.freeze it:

"use strict";
const b = Object.freeze({foo: Object.freeze({bar: 42}), baz: 7});
b.baz = {hello: "world"}; // Error: Invalid assignment in strict mode

Upvotes: 2

Related Questions