Ask Your Question

In Javascript, is it possible to Deep Freeze an object and all its child elements in a straightforward manner?

asked 2022-10-27 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2021-09-10 05:00:00 +0000

pufferfish gravatar image

Yes, it is possible to deeply freeze an object in JavaScript using the Object.freeze() method recursively on all its nested properties. Here is an example code snippet to achieve this:

function deepFreeze(obj) {
  Object.getOwnPropertyNames(obj).forEach(prop => {
    if (obj.hasOwnProperty(prop) && obj[prop] !== null && (typeof obj[prop] === "object" || typeof obj[prop] === "function") && !Object.isFrozen(obj[prop])) {
  return obj;

const obj = {
  prop1: {
    nestedProp: {
      array: [1, 2, 3]
  prop2: "hello"


// Trying to modify any properties of the object would fail silently in strict mode
obj.prop2 = "world"; // This would have no effect
obj.prop1.nestedProp.array.push(4); // This would also have no effect
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2022-10-27 11:00:00 +0000

Seen: 9 times

Last updated: Sep 10 '21