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:
// make an object
const myObject = {
myProp1: 2,
myProp2: "my value"
}
// make the object ready-only
Object.freeze(myObject)
// try to change the object's property value
myObject.myProp1 = 3
// hint: you can't
console.log(myObject.myProp1)
// 2
However, if a property contains a nested object, then the properties of the nested object can still change:
const myObject = {
myProp1: 2,
myProp2: {
myNestedProp: "my value"
}
}
Object.freeze(myObject);
myObject.myProp2.myNestedProp = "your value"
console.log(myObject.myProp2.myNestedProp)
// "your value"