snippetjavascriptTip
How can I deep freeze an object in JavaScript?
Viewed 0 times
objectjavascriptdeephowfreezecan
Problem
Objects in JavaScript are mutable, regardless if you define them as
In order to make an object immutable, you can use either
Both of these methods prevent new properties from being added and existing properties from being removed. Additionally,
| | Create | Read | Update | Delete |
| --- | --- | --- | --- | --- |
const variables or not. In fact, using const when defining an object only prevents the variable from being reassigned. However, you can reassign the properties of a const object or array.In order to make an object immutable, you can use either
Object.freeze() and Object.seal(). Although similar, they have a key difference that you need to remember.Both of these methods prevent new properties from being added and existing properties from being removed. Additionally,
Object.freeze() also prevents existing properties from being altered. The reason for that is that Object.seal() only marks existing properties as non-configurable, meaning their values can be changed as long as they are writable.| | Create | Read | Update | Delete |
| --- | --- | --- | --- | --- |
Solution
const myObj = { a: 10, b: 20, c: 30 };
myObj.a = 12; // { a: 12, b: 20, c: 30 };
const myArr = [15, 25, 35];
myArr[1] = 28; // [15, 28, 35];Both of these methods prevent new properties from being added and existing properties from being removed. Additionally,
Object.freeze() also prevents existing properties from being altered. The reason for that is that Object.seal() only marks existing properties as non-configurable, meaning their values can be changed as long as they are writable.| | Create | Read | Update | Delete |
| --- | --- | --- | --- | --- |
|
Object.freeze() | No | Yes | No | No ||
Object.seal() | No | Yes | Yes | No |> [!TIP]
Code Snippets
const myObj = { a: 10, b: 20, c: 30 };
myObj.a = 12; // { a: 12, b: 20, c: 30 };
const myArr = [15, 25, 35];
myArr[1] = 28; // [15, 28, 35];const frozen = Object.freeze({ username: 'johnsmith' });
const sealed = Object.seal({ username: 'johnsmith' });
frozen.name = 'John Smith'; // frozen = { username: 'johnsmith' }
sealed.name = 'John Smith'; // sealed = { username: 'johnsmith' }
delete frozen.username; // frozen = { username: 'johnsmith' }
delete sealed.username; // sealed = { username: 'johnsmith' }
frozen.username = 'jsmith'; // frozen = { username: 'johnsmith' }
sealed.username = 'jsmith'; // sealed = { username: 'jsmith' }const myObj = {
a: 1,
b: 'hello',
c: [0, 1, 2],
d: { e: 1, f: 2 }
};
Object.freeze(myObj);
myObj.a = 10;
myObj.b = 'hi';
myObj.c[1] = 4;
myObj.d.e = 0;
/*
myObj = {
a: 1,
b: 'hello',
c: [0, 4, 2],
d: { e: 0, f: 2 }
}
*/Context
From 30-seconds-of-code: deep-freeze-object
Revisions (0)
No revisions yet.