Skip to content

Instantly share code, notes, and snippets.

@afterburn
Last active May 14, 2019 08:26
Show Gist options
  • Save afterburn/68a97b6eb0a65d00038f17a30b6ecd46 to your computer and use it in GitHub Desktop.
Save afterburn/68a97b6eb0a65d00038f17a30b6ecd46 to your computer and use it in GitHub Desktop.
Recursively freezes an object to make it fully immutable.
function deepFreeze (obj) {
Object.freeze(obj)
Object.values(obj).forEach((value) => {
if (typeof value === 'object') {
deepFreeze(value)
}
})
}
const user = {
name: 'john',
wallet: {
balance: 100
}
}
deepFreeze(user)
user.name = 'bob'
user.wallet.balance = 99999
console.log(user)
// {
// name: 'john',
// wallet: {
// balance: 100
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment