4 ms·
How do you feel about `const` for variables that are not reassigned but are still mutated? const array = [1, 2, 3]; array.push(100); // unexpected? I
by millstone 10y ago
How do you feel about `const` for variables that are not reassigned but are still mutated?
const array = [1, 2, 3];
array.push(100); // unexpected?
I prefer to use let for bindings to objects that get mutated, even if the variable is not re-bound.
- madamelic 10y agoYeah, I wrestled with that briefly. For anyone not in the know, declaring `const` on an object only makes it where you can't re-assign the object, but you can still mutate its 'members'. Personally, I use `let` just to symbolize that it isn't a constant and does change even though I could declare it a `const`. I think it makes the code more readable.
- btown 10y agoAs far as I know, the "correct" approach is to act as if every object is deeply frozen (perhaps actively testing using Object.freeze... IMO https://github.com/ecomfe/babel-plugin-freeze-const https://github.com/ecomfe/babel-plugin-freeze-const has the right idea but is nothing more than an idea), and transform things into new objects functionally, using .map and friends. The problem is that, while a lot of things can be expressed elegantly this way, sometimes the most maintainable thing, or the most efficient thing, is to have some side effects in a deep loop in a certain algorithm, and it's very difficult to do this with purely functional JS. The real solution is to allow your const bindings to be mutated when you need to, and comment explicitly to make things perfectly clear!
- deleted 10y ago[deleted]