Is there any reason to freeze an object other than an array or an explicit "object"

Viewed 36

In JavaScript, I understand why one would use Object.freeze() on an array or object, as it prevents shallow modification to anything contained within it, but is there any reason to use it on something else? A Boolean, String, RegExp, Number, a custom class?

Specifically, I am wondering about anonymous functions, although anything I learn here will probably be of use to me somewhere along my road.

1 Answers

It is not good to do it with classes because Classes must be mutable objects to modify its attributes and in some cases their states. But it can be a good approach to do it if you are just passing that value to a deep nested function. But this method does not affect primitive types, you can try

let value = Object.freeze(true)
value = false
console.log(value) // Output => false

You will see that this does not produce any error, so there is no good reason to use it with primitives.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

Related