Reputation: 2141
Despite the fact that a const
cannot be assigned to in ECMAScript 2015, the object can be modified if it isn't frozen with Object.freeze
.
Since a const
is supposed to be immutable, would it make sense to add Object.freeze
to freeze the object?
Most use cases would not require the contents being modifiable after being declared. One exception I thought of would be assigning a class
to a const
(e.g. const MyClass = class MyClass {}
), in which case the properties would need to be changeable (at least for most uses).
I'm not talking about whether ECMAScript 2015 should be changed; I was wondering about whether I should use Object.freeze
for const
s in everyday code.
const firstNames = ['John', 'Daisy'];
firstNames = [] // Fails silently
firstNames // => ['John', 'Daisy']
firstNames[0] = 'Replaced!'; // No error and it works!
firstNames // => ['Replaced!', 'Daisy']
Object.freeze
const firstNames = Object.freeze(['John', 'Daisy']);
firstNames = [] // Throws an error
firstNames // => ['John', 'Daisy']
firstNames[0] = 'Replaced!'; // No error and it works!
firstNames // => ['Replaced!', 'Daisy']
Upvotes: 4
Views: 286
Reputation: 664599
Should I use Object.freeze for consts in everyday code?
Yes, I think that would be a good practise. It does give you the same advantages as const
- failing on mistakes instead of carrying on (in strict mode, of course). It's also a more declarative style of code, clearly stating the intention that the object is not supposed to be mutated.
Yet, iirc frozen objects are still a bit slower than normal ones. If you have really performance-critical code, you'll have to know this. It shouldn't stop you from using Object.freeze
in general, though1.
You shouldn't however rely on the exceptions thrown when accessing frozen objects. It's likely that you have to transpile your code to ES3 where freezing is not supported.
1) And the more people use it every day, the sooner engines will optimise this - it's overdue imo :-)
Upvotes: 3