const info = [1,2,3,4]
const newInfo = info.splice(2);
'info' has changed
const info = [1,2,3,4]
const newInfo = info.splice(2);
'info' has changed
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/Referen...
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.
const number = 1337;
number = 10; // fails
But objects/arrays are not immutable in js, so you can do this:
const person = { name: 'Dude' };
person.name = 'Dudette';
Which is perfectly valid. If you want full immutability, i recommend you check out https://facebook.github.io/immutable-js/, been running it in production, a real pleasure to work with.
Only in development mode, by freezing the objects.
function deepFreeze(obj) {
const out = Object.freeze(obj);
Object.keys(out).forEach(key => {
if (typeof out[key] === 'object') {
out[key] = Object.freeze(out[key]);
}
});
return out;
}(recursive)
Rust has similar semantics: https://is.gd/hsRjPh versus https://is.gd/ROgzXl
IIRC you can also declare const objects in C++, but constness is more complex and overridden there.