3 ms·
The const keyword makes the object reference constant. It doesn't make the object's value constant. You can change the contents of 'info' (info.push(5) is fine)
by josephg 10y ago
The const keyword makes the object reference constant. It doesn't make the object's value constant. You can change the contents of 'info' (info.push(5) is fine). You just can't change which object the variable points to. (info = [] will throw).
If you know C/C++, the code 'const info = []' makes 'info' a constant pointer to a list not a pointer to a constant list.
If you want to stop a variable from being changed, use Object.freeze() - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze https://developer.mozilla.org/en/docs/Web/JavaScript/Referen...
- samcodes 10y agoThis was what I came to comment on; when introducing ES6 features, this always trips people up. Thanks for "constant pointer to a list, not pointer to a constant list", I will use that next time I explain this. This also means that objects defined with const can be mutated: const x = { y: 2 }; x.y = 3; Doesn't error. However with types that are immutable, like numbers and strings, const really is a constant: const HELLO = "hi" will never change.
- deleted 10y ago[deleted]