If the variable foo is a const that points to an object — we can’t make foo point to another object later on:
const foo = {};
foo = {}; // TypeError: Assignment to constant variable.
But we can however mutate, make changes to, the object foo points to, like so:
const foo = {};
foo['prop'] = "Moo"; // This works!
console.log(foo);
If we want the value of foo to be immutable we have to freeze it using Object.freeze(…).
When we freeze an object we can’t change it, we can’t add properties or change the values of properties, like so:
const foo = Object.freeze({});
foo.prop = 123;
console.log(foo.prop) // undefined
const foo = {};
foo = {}; // TypeError: Assignment to constant variable.
But we can however mutate, make changes to, the object foo points to, like so:
const foo = {};
foo['prop'] = "Moo"; // This works!
console.log(foo);
If we want the value of foo to be immutable we have to freeze it using Object.freeze(…).
When we freeze an object we can’t change it, we can’t add properties or change the values of properties, like so:
const foo = Object.freeze({});
foo.prop = 123;
console.log(foo.prop) // undefined
No comments:
Post a Comment