Skip to content

Instantly share code, notes, and snippets.

@tarunluthra123
Created June 3, 2021 07:49
Show Gist options
  • Save tarunluthra123/404a6eb18ba80b180ea4f3425bbc8232 to your computer and use it in GitHub Desktop.
Save tarunluthra123/404a6eb18ba80b180ea4f3425bbc8232 to your computer and use it in GitHub Desktop.
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