Menu

gitpiper

deepFreeze javascript Code Snippet in 2024

objectrecursionintermediate

Last Updated: 15 December 2024

Deep freezes an object.

  • Use Object.keys() to get all the properties of the passed object, Array.prototype.forEach() to iterate over them.
  • Call Object.freeze(obj) recursively on all properties, applying deepFreeze() as necessary.
  • Finally, use Object.freeze() to freeze the given object.
const deepFreeze = obj => { Object.keys(obj).forEach(prop => { if (typeof obj[prop] === 'object') deepFreeze(obj[prop]); }); return Object.freeze(obj); };
'use strict'; const val = deepFreeze([1, [2, 3]]); val[0] = 3; // not allowed val[1][0] = 4; // not allowed as well

javascript snippet similar to deepFreeze For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️