4 ms·
Similar confusion in Java Script regarding const vs var.
by johnhenry 9y ago
Similar confusion in Java Script regarding const vs var.
- skrebbel 9y agoI like to overuse let for signalling mutable content. In other words, I only use const when the variable is read-only and never to be mutated. Even by that narrower ruleset, nearly all variables end up being const. This way a "let" signals to the reader "watch out, something is going to be mutated here", which IMO is a more useful note to the reader than "watch out, this reference can be changed".
- johnhenry 9y agoPerhaps I should have stated "const vs let", with "let" being JavaScript's modern, scoped version of "var"... but even so, I think this is just the sort of confusion that the author is trying to clear up. "let" in JS doesn't mean "mutable" just as "var" in Kotlin doesn't either. While one can use them as reminders to the programmer as to the mutability of the underlying object, there is nothing in the language that enforces this, so this is technically, syntactically incorrect. In both languages, it might make more sense to simply label variables directly with something like `${variable name}_IMMUTABLE`, which gives a clear clue to the programmer that the variable is immutable, but doesn't imply anything that's untrue about the how the language is used. Further, one can assign these variables using a library like immutable.js (https://facebook.github.io/immutable-js/ https://facebook.github.io/immutable-js/), or Kotlin's immutable collections (https://github.com/Kotlin/kotlinx.collections.immutable https://github.com/Kotlin/kotlinx.collections.immutable) to enforce a mechanism for mutability.
- blauditore 9y agoWhy not just Object.freeze()?
- johnhenry 9y agoFreezing an object doesn't freeze it's children, and thus it's still technically mutable. I think using deep-freeze (https://github.com/substack/deep-freeze https://github.com/substack/deep-freeze) might work.
- irishsultan 9y agoBecause that doesn't do what people want/expect, if you have a key with a value that's not frozen it will still be mutable, which indirectly mutates your object. See the example at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze https://developer.mozilla.org/en/docs/Web/JavaScript/Referen... about modifying internal.a
- sjrd 9y agoNo, it isn't the same confusion. The article describes a different problem (worse, IMO). Read it again, or read the following comment in this HN thread: https://news.ycombinator.com/item?id=14445829 https://news.ycombinator.com/item?id=14445829
- johnhenry 9y agoAgreed, I don't believe that the confusions are the same, only similar.
- deleted 9y ago[deleted]