3 ms·
Using the mantra code is communication, declaring everything as const lets others (and your future self) know that as of last writing they can expect this varia
by aquilaFiera 11y ago
Using the mantra code is communication, declaring everything as const lets others (and your future self) know that as of last writing they can expect this variable to not be reassigned. I think that small piece of information can be useful.
To your point however, `const` does not imply constant in the sense of other languages (like `.freeze()` does) so it does mean your target future audience is someone who is familiar with some of the nuances of recent JavaScript, an assumption that can be dangerous to make.
For my recent ES6 escapades I've been using the pattern of `const` first and `let` only when mutability of assignment is needed and I have yet to have that bite me in the ass. However this has been small projects and I can't speak for a larger codebase.
- Nullabillity 11y ago> To your point however, `const` does not imply constant in the sense of other languages (like `.freeze()` does) so it does mean your target future audience is someone who is familiar with some of the nuances of recent JavaScript, an assumption that can be dangerous to make. Does any other language than Rust implement it this way? I know Rust needs to, for the borrowing semantics. Java does it the same way as JS. Scala and Haskell both make everything immutable by default as convention, but there's nothing preventing you from mutating a `var` field of a `val` reference, or abusing `unsafePerformIO` to modify an `IORef` from a supposedly pure context.
- jharger 11y agoC++ Assume you have a class Foo, and this: const Foo fooInst(1, 2, 3); if you try to call a method foo.bar() you can't, unless that method bar() is also marked const with this type of signature: int bar() const; Meaning that bar returns an int, but can't assign to any fields or call any other non-const methods. Although, it does have this hideous const_cast<> operator that anyone can use to break these rules.