Re:JavaScript variables: var and let and const
by saagarjha on Friday March 06, 2020 @02:23PM
(#22506411)
Does JavaScript have value types where const might work the way the first author expects it to?
[ Parent
| on HN ]
Re:JavaScript variables: var and let and const
by leftyted on Friday March 06, 2020 @02:37PM
(#22506535)
symbol/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.
Re:JavaScript variables: var and let and const
by threatofrain on Friday March 06, 2020 @02:35PM
(#22506511)
In 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.
Re:JavaScript variables: var and let and const
by dragonwriter on Friday March 06, 2020 @04:37PM
(#22507560)
JavaScript not only has (a small set of) value types, it also has frozen objects.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Re:JavaScript variables: var and let and const
by 52-6F-62 on Friday March 06, 2020 @03:13PM
(#22506869)
I 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.
Re:JavaScript variables: var and let and const
by austincheney on Friday March 06, 2020 @02:29PM
(#22506453)
No. 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.