Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to completely restrict the modification of properties of a const object [duplicate]

Tags:

javascript

Even after using strict mode, I am able to update the object variable. How is possible? Is it possible to create constant objects at all?

"use strict";

const x = {a:"sss"}
x.a = "k"
console.log(x)

outputs:

{ a: 'k' }
like image 766
overflower Avatar asked Dec 24 '22 18:12

overflower


2 Answers

Okay - so it is required to use Object.freeze call t make the object unchangeable. Even the strict mode isn't required.

const x = {a:"sss"}
Object.freeze(x);

x.a = "k"
console.log(x)

Outputs:

x.a = "k"
    ^

TypeError: Cannot assign to read only property 'a' of object '#<Object>'
like image 111
overflower Avatar answered Jan 29 '23 23:01

overflower


ES6 const is not about immutability.

const only creates a read-only reference and that means that you cannot reassign another value for the object.

const creates an immutable binding and guarantees that no rebinding will happen.

Using an assignment operator on a const variable throws a TypeError exception:

Short example:

const x = {a:"sss"}
x={a:"k"}
console.log(x)

You will see the following message:

"Uncaught TypeError: Assignment to constant variable."

like image 32
Mihai Alexandru-Ionut Avatar answered Jan 30 '23 00:01

Mihai Alexandru-Ionut