Skip to content

Instantly share code, notes, and snippets.

@tarunluthra123
Created Jun 3, 2021
Embed
What would you like to do?
Deep Freezing a JS object
"use strict";
function deepFreeze(obj) {
// Freeze properties first. Then freeze self.
const properties = Object.getOwnPropertyNames(obj);
// Iterate over the properties and get their values.
// Check if the value if not null and is an object itself.
// If so, recursively freeze it.
for (const property of properties) {
const value = obj[property];
if (value && typeof value === "object") {
deepFreeze(value);
}
}
return Object.freeze(obj);
}
const spidey = deepFreeze({
name: {
first: "Peter",
last: "Parker",
},
alias: "Spiderman",
profession: "Photographer",
villains: ["Green Goblin", "Electro", "Venom", "Mysterio"],
});
spidey.name.middle = "Benjamin";
spidey.villains.push("Doc Ock");
console.log(spidey);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment