Hacker News new | ask | show | jobs
by spraak 3691 days ago
This right here. One of my friends (a more experienced developer) told me at coffee one day, "I use const for everything" which really stuck with me. It really helps make it clear if you need a mutation to have let stand out.
2 comments

However, it's worth noting that using const doesn't make variables immutable. It only protects them of being reassigned:

const val = 'a'; val = 'b'; // TypeError

const obj = { val: 'a' }; obj.val = 'b'; // This line will still work.

obj = { val: 'b' }; // TypeError

Yep. In those cases, I still prefer let personally even though I know the variable itself will not be re-assigned, kind of as an indicator that I expect the referenced object to be mutated.
Coming from a background that includes some experience with C / C++, `const` here works as I expect it to. I'd prefer `const` even for the object reference case: I get errors on reassignment this way, and presumably it makes additional optimizations possible. To each their own, I suppose :)

There's also `Object.defineProperty()`, `Object.freeze()` for more control over mutability.

I just wish let was in fact const (and something like "local" could be let), simply because the keyword let is nicer to type, easier to read, and more importantly better in line with the meaning of let in Lisp/Scheme/ML/OCaml/et al.
Yeah, I was thinking the same! I was even considering writing a custom babel transform to do this for me :P