Files
30-seconds-of-code/snippets/deepFreeze.md
Angelos Chalaris 611729214a Snippet format update
To match the starter (for the migration)
2019-08-13 10:29:12 +03:00

525 B

title, tags
title tags
deepFreeze object,recursion,intermediate

Deep freezes an object.

Calls Object.freeze(obj) recursively on all unfrozen properties of passed object that are instanceof object.

const deepFreeze = obj =>
  Object.keys(obj).forEach(
    prop =>
      !(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
  ) || Object.freeze(obj);
'use strict';

const o = deepFreeze([1, [2, 3]]);

o[0] = 3; // not allowed
o[1][0] = 4; // not allowed as well