JavaScript read-only objects

freezing objects to make them

// updated 2025-05-11 11:34

We can use the Object.freeze(object) method to make an object and its property values read-only:

1// make an object
2const myObject = { 
3  myProp1: 2, 
4  myProp2: "my value" 
5}
6
7// make the object ready-only
8Object.freeze(myObject)
9
10// try to change the object's property value
11myObject.myProp1 = 3
12
13// hint: you can't
14console.log(myObject.myProp1)
15// 2

However, if a property contains a nested object, then the properties of the nested object can still change:

1const myObject = { 
2  myProp1: 2, 
3  myProp2: { 
4    myNestedProp: "my value" 
5  }
6}
7
8Object.freeze(myObject);
9
10myObject.myProp2.myNestedProp = "your value"
11
12console.log(myObject.myProp2.myNestedProp)
13// "your value"
⬅️ older (in textbook-javascript)
📒 JavaScript nullish coalescing
⬅️ older (in code)
📒 JavaScript nullish coalescing
newer (in code) ➡️
React — an introduction ⚛️
⬅️ older (posts)
📒 JavaScript nullish coalescing
newer (posts) ➡️
React — an introduction ⚛️