JavaScript Interview Question #36
What does Object.freeze() do?
Objects, Arrays & Core Data Handling Junior Beginner
Quick Interview Answer
Object.freeze prevents adding, deleting, or changing the object's own properties and makes those properties non-configurable. In strict mode, invalid mutation attempts can throw errors.
Detailed Explanation
Object.freeze prevents adding, deleting, or changing the object's own properties and makes those properties non-configurable. In strict mode, invalid mutation attempts can throw errors.
Object.freeze is shallow. Nested objects are not automatically frozen, so a recursive strategy is required when deep immutability is needed.
Code Example
const settings = Object.freeze({
theme: "dark",
options: {
pageSize: 20
}
});
// settings.theme = "light"; // Not allowed
settings.options.pageSize = 50; // Nested object is not frozen
console.log(settings.options.pageSize); // 50