How to completely limit the modification of const object properties

Even after using strict mode, I can update the object variable. How is this possible? Can permanent objects be created at all?

"use strict";

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

outputs:

{ a: 'k' }
+4
source share
2 answers

Good - therefore, you need to use the call to Object.freeze t to make the object immutable. Even strict mode is not 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>'
+5
source

ES6 is const not about immutability .

const creates a read-only link, which means that you cannot reassign another value to the object.

constcreates immutable bindingand guarantees that it will not rebinding.

assignment operator const TypeError:

:

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

:

"Uncaught TypeError: .

+5

Source: https://habr.com/ru/post/1676979/


All Articles