Object.freeze
is a handy tool that helps you make an object immutable in JavaScript.
Object.freeze(someObject);
If you try use the delete
keyword or an assignment operator =
after freezing the object with Object.freeze
it will remain unchanged.
// declare the object
const frozenUser = {
name: 'Jill',
age: '22',
isLearning: true
};
// freeze!
Object.freeze(frozenUser);
// an attemp to delete a propery and alter one
delete frozenUser.age;
frozenUser.isLearning = false;
// a proof that the object hasn't changed
console.log(frozenUser.name); // John
console.log(frozenUser.age); // 22
console.log(frozenUser.isLearning); // true
Once we’ve applied Object.freeze
to the frozenUser
object, it became immutable. Neither
the delete
, nor the assignment operator =
worked.