3 ms·
Does JavaScript have value types where const might work the way the first author expects it to?
by saagarjha 7y ago
Does JavaScript have value types where const might work the way the first author expects it to?
- austincheney 7y agoNo. The only thing that makes const unique from let is that references declared as constants cannot be reassigned or else an error will be thrown. The exclusion only applies to the reference name itself and not to any of its properties as the article articulates.
- deleted 7y ago[deleted]
- threatofrain 7y agoIn JS, I think of any reference to an object as a pointer, and the <pointer> is immutable even if its contents aren't; then everything in JS which can be considered a value which is immutable under const. IMO it's not just a problem of const vs let, because it'll pop up again when you're trying to copy a JavaScript object, and it'll pop up again when someone has questions about garbage collection.
- leftyted 7y agosymbol/boolean/string/number are immutable and work how you'd expect with const because they are immutable. Unsure if that makes them "value types". I think the article is a bit silly. Calling it "const" was a mistake but that's a naming issue. JS's "const" is the same as Java's "final," right? It communicates something useful.
- 52-6F-62 7y agoI won't repeat the other comments, but I'll note that you can make the additional, uglier step to get the results the first author expects by (as suggested) treating the assignment as a pointer to the object and rendering the object immutable. const myObject = Object.freeze({ myValue: "Something", }); The problem with that is `Object.freeze` doesn't act on nested objects, so you usually have to have some other method/macro to do that for you. You might be able to do that with decorators in TS. It works on Object and Array types, but not on other primitive types. That part is frustrating. It would certainly be nice to have a single method for rendering any value immutable, whether it was the initial assignment or a built-in.
- dragonwriter 7y agoJavaScript not only has (a small set of) value types, it also has frozen objects. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...