Skip to content

Instantly share code, notes, and snippets.

Created June 3, 2021 07:49
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") {
return Object.freeze(obj);
const spidey = deepFreeze({
name: {
first: "Peter",
last: "Parker",
alias: "Spiderman",
profession: "Photographer",
villains: ["Green Goblin", "Electro", "Venom", "Mysterio"],
}); = "Benjamin";
spidey.villains.push("Doc Ock");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment