To ensure that an object is deep-frozen, you will have to create a recursive function for freezing each property of type object: Without deep freeze.

BY Best Interview Question ON 02 Jul 2021

Example

let person = {
    name: "Ankit",
    profession: {
        name: "content writer"
    }
};
Object.freeze(person);
person.profession.name = "content writer";
console.log(person);

Output { name: 'Ankit', profession: { name: 'content writer' } }

Now, using Deep Freeze for the object,

function deepFreeze(object) {
    let propNames = Object.getOwnPropertyNames(object);
    for (let name of propNames) {
        let value = object[name];
        object[name] = value && typeof value === "object" ?
            deepFreeze(value) : value;
    }
    return Object.freeze(object);
}
let person = {
    name: "Ankit",
    profession: {
        name: "content writer"
    }
};
deepFreeze(person);
person.profession.name = "content writer";

Suggest An Answer