by aphexairlines · 11y ago · 0 comments
As a reader, I know that after reading a const line I don't have to check if someone rebinds this name before each use site -- it's impossible.
Interpreters and static analysis tools use this information to stop you when you write a piece of code that rebinds the name, asking "did you really mean to do that? You said you wouldn't."
This turns out to be almost useless information for most of us, since the real problem is not re-assignment, but mutation of the value (in the case of non-primitives).
`const x = 2` feels great emotionally, but `const x = [2]` has the feeling of safety without any of the guarantee.
This is a classic case (quoted from Crockford regularly) of a utility that it sometimes useful and sometimes harmful (aka not useful), and there's a better option (`let`), so the better option should generally be preferred.
I only use `const` (refactor from `let`) when a piece of code is reasonably complete and I'm pretty sure re-assignment will not ever be appropriate. Guessing at that before writing the code is a premature optimization.
And guessing wrongly and having to refactor back to `let` later is more risky.
Const is perfectly sensible with references to mutable objects too. The latter guarantees that x will always point to the same mutable array. If you pass a reference to the x array to a function which needs to mutate that specific array or observe it for changes, then it may be important that x is never rebound to a different array. Consider the following code:
const x = [5,6,7];
Object.observe(x, function(changes) {
console.log('changes', changes);
});
// ...
// time to clear the array
// WRONG! The code observing changes to the old x array will not see
// this change or future changes to this new array. Because we used const, this
// will trigger an error and immediately show us our mistake.
x = [];
// CORRECT. This mutates the array instead of creating a new empty array.
x.length = 0;This notion (concern) is meaningless in JS, since when you pass any reference, it's always a reference-copy, so there's no value nor assistance that `const` provides.