News for hackers. Stuff that matters.
Re:JavaScript variables: var and let and const by dlbucci on Friday March 06, 2020 @02:12PM (#22506328)
Having used Kotlin for a while now, I find it really unfortunate that `const` wasn't `val` for the sole reason that it's 5 characters instead of 3. `val` would have matched nice with `let`, and my multi-variable declaration statements could have had a nice 4-space indentation while still being all aligned.

I know it can be confused with `var`, but no one should ever use that now that `let` exists.

One of these days I'll write my own little language that compiles to TypeScript or something and fix that :)

Re:JavaScript variables: var and let and const by bryanrasmussen on Friday March 06, 2020 @03:22PM (#22506958)
I'm supposing the reason const is const is because it was in the list of reserved words quite early https://www-archive.mozilla.org/js/language/E262-3.pdf section 7.5.3 Future Reserved Words - whereas of course val is probably a really common variable name in multitudinous little scripts all over the world and it would basically break the internet if it was used.

I would suggest con, but hey that would probably also break a lot of stuff and const wouldn't break anything because being a reserved word you should never have named or been able to name your variable const (probably some JavaScript engine somewhere would have let you though, like early IE/Netscape might have made that mistake)

Re:JavaScript variables: var and let and const by hombre_fatal on Friday March 06, 2020 @03:14PM (#22506871)
A solution I prefer is Rust's where the immutable binding is default "let x" and you opt-in with a modifier to make it mutable "let mut x".

It just makes sense for the immutable case to be default by design instead of just by developer habit.

"var" vs "val" always were too similar for me.

Re:JavaScript variables: var and let and const by bobbylarrybobby on Friday March 06, 2020 @06:01PM (#22508176)
Swift’s var and let are also good. There is no “default” but “let” is obviously preferred
Re:JavaScript variables: var and let and const by melling on Friday March 06, 2020 @02:29PM (#22506457)
I like that Swift has var and let. Having the first letter be different means less typing with autocompletion.

I suppose when I get to use voice recognition for coding, there will also be less confusion.

Re:JavaScript variables: var and let and const by eyelidlessness on Friday March 06, 2020 @02:52PM (#22506678)
Generally speaking most languages treat `let` as constant/immutable, and the real shame is that JS did not. It's understandable why (they needed a block-scoped `var`), but unfortunate nonetheless.
Re:JavaScript variables: var and let and const by chrisseaton on Friday March 06, 2020 @03:46PM (#22507147)
> for the sole reason that it's 5 characters instead of 3

Are you being charged by the character or something?

Re:JavaScript variables: var and let and const by setr on Friday March 06, 2020 @03:53PM (#22507203)
Formatting..!
Re:JavaScript variables: var and let and const by dkarl on Friday March 06, 2020 @03:35PM (#22507078)
My experience with Scala is that `var` and `val` fortunately look very different in source code. `var` jumps right out at me, perhaps because the shape of the word is so different.
Re:JavaScript variables: var and let and const by masswerk on Friday March 06, 2020 @11:10PM (#22509679)
Mind that JavaScript simply reused the set of reserved keywords from Java. This similarity in keywords and syntax is, what made the "Java" part in "JavaScript", while there is actually no deeper relation between the two languages. `const` was available. (However, `let` wasn't in that set, nor in the reserved ECMA extension.)
Re:JavaScript variables: var and let and const by the_other_b on Friday March 06, 2020 @04:14PM (#22507368)
Genuine question (and hoping for your opinion here), why would I use Kotlin over Java? Outside the obvious like developing on Android.

I haven't had much exposure to it, but it seems like it has a wider breadth of features and has a quicker development speed?

Re:JavaScript variables: var and let and const by rkrishnaan on Friday March 06, 2020 @04:24PM (#22507449)
Re:JavaScript variables: var and let and const by mpoteat on Friday March 06, 2020 @04:52PM (#22507679)
If you like terse code I recommend APL.
Re:JavaScript variables: var and let and const by jakub_g on Friday March 06, 2020 @03:23PM (#22506967)
There's one non-obvious corollary from the fact that using let/const before declaring throws an error and var does not:

If you have let/const in your source code, but you use babel to transform it to ES5, you may have cases where you use let/const in that error-throwing way, but it's compiled down to var, and all is good (apart from variable being undefined when used).

When you however upgrade your babel conf to output ES6 and not compile down to var, you'll be having reference errors in those places, which may explode your app. I learned in production after enabling "differential serving" (module/nomodule).

There's an eslint plugin that can check for this stuff, but it finds false positives in 95% of cases (matter of personal preference - it disallows "valid but not blessed by the authors" behavior), so it's very likely you don't have it enabled, just like us.

Re:JavaScript variables: var and let and const by _bxg1 on Friday March 06, 2020 @03:36PM (#22507084)
Oof. I was surprised for a second that Babel would simply put "var" in there instead, when it expressly doesn't do the same thing. But then I realized that emulating block scope without let would mean wrapping all blocks in anonymous functions, which would carry significant overhead.

Gross.

Re:JavaScript variables: var and let and const by thewarrior on Friday March 06, 2020 @07:52PM (#22508876)
So transpiling down to ES5 doesn’t preserve semantics ?
Re:JavaScript variables: var and let and const by jakub_g on Saturday March 07, 2020 @01:18PM (#22513053)
For some features, having 100% spec compliant behavior in transpiled code would mean excruciatingly slow/bloated code, or be downright impossible. There's a reason why features are added to the language after all: to add things that are impossible or too complex to write in old version of language.

Transpilation is "best effort" and involves some tradeoffs.

Re:JavaScript variables: var and let and const by rofo1 on Friday March 06, 2020 @04:25PM (#22507464)
Use const always, unless you must use let. That's it.

You don't need to read other articles on this subject, it's that simple.

Re:JavaScript variables: var and let and const by DaiPlusPlus on Friday March 06, 2020 @04:49PM (#22507655)
`var` creates global properties when used in the global scope, which is useful at times.
Re:JavaScript variables: var and let and const by neurotrace on Friday March 06, 2020 @07:13PM (#22508631)
If you really, really need a global then you should assign it to `window/global/globalThis` instead of relying on the weird behavior of `var`
Re:JavaScript variables: var and let and const by wolco on Saturday March 07, 2020 @04:16AM (#22510740)
What do you find weird about var?
Re:JavaScript variables: var and let and const by DaiPlusPlus on Monday March 09, 2020 @04:22AM (#22523834)
It's weird because it has side-effects (namely, implicitly adding/setting a named property in the current scope object, if any).

It means that a top-level script using `var` that is subsequently refactored into a scoped function somewhere will now have different semantics and might break if other code depended on `var` creating a new global property.

Re:JavaScript variables: var and let and const by cryptica on Saturday March 07, 2020 @02:41AM (#22510386)
I use `let` mostly and I only use `const` for special cases when changing the variable would break the program and I want to constrain future developers from doing that. For example, when I import some library references in Node.js using `require`, I will use `const` or if I need to define a magic number like `const HANDSHAKE_TIMEOUT = ...`.

I don't see the point of using const everywhere though because I don't code in a pure functional style and I don't pretend to.

Often, it makes sense to re-assign a variable and I don't want to mislead future developers into thinking that it's not OK to do so if the requirements have changed.

Re:JavaScript variables: var and let and const by cwmma on Friday March 06, 2020 @03:58PM (#22507229)
the one thing that annoys me about let/const that leads to me occasionally using var is that with var you can declare a variable in a try block and then use it afterwards, instead I have to declare a let outside the try or put way more then I want to in the try.
Re:JavaScript variables: var and let and const by dragonwriter on Friday March 06, 2020 @04:33PM (#22507516)
But, why would you want the declaration in the try when the scope of the variable is broader? It's true that var let's you do that, but it seems to me that's strictly a misleading thing.

Sure, you’ll often need to split declaration from assignment with let in that case, but that's not a bad thing, IME.

Re:JavaScript variables: var and let and const by madacol on Friday March 06, 2020 @06:24PM (#22508340)

    try {
        const { attribute1, attribute2 } = getObject()
    } catch () {}
    attribute1 // undefined
How would you solve that?
Re:JavaScript variables: var and let and const by dragonwriter on Friday March 06, 2020 @10:34PM (#22509557)
With let outside the try, because that's the intended scope. Insofar as there is a problem I see with that, it's that you can't separate declaration of a single-assignment value (const) from the one allowed assignment, because the ideal solution would be const declared outside the try with the assignment inside.

OTOH var declared inside is a bad solution because it's both misleading as to scope and using a freely-assignable variable for something that's logically single-assignment. Let outside has only one of those problems.

Re:JavaScript variables: var and let and const by madacol on Saturday March 07, 2020 @08:56AM (#22511539)
Exactly, I'm just pointing out the limitations of `let/const`

I usually solve that case with

    let attribute1, attribute2;
    try {
         const object = getObject()
         attribute1 = object.attribute1
         attribute2 = object.attribute2
    } catch () {}
But I'm just not satisfied with it, too many statements. And it gets really messy with many attributes
Re:JavaScript variables: var and let and const by decentralised on Sunday March 08, 2020 @08:31AM (#22517704)
How about this:

    let attribute1, attribute2;
    try  {
     ({attribute1, attribute2} = getObject())
    } catch (e) {}
Re:JavaScript variables: var and let and const by madacol on Sunday March 08, 2020 @09:38PM (#22522155)
wow, didn't know that!

So parenthesis are the trick, thanks!

Re:JavaScript variables: var and let and const by decentralised on Monday March 09, 2020 @03:28AM (#22523603)
No problem!
Re:JavaScript variables: var and let and const by ht85 on Friday March 06, 2020 @04:33PM (#22507524)
It would be nice if you could assign the result of a try / catch (or any block) to a variable, you can kind of emulate it with an IIFE:

    const outer = (() => {
      try {
        ...
        return ...
      } catch (error) {
        ...
      }
    })()
Re:JavaScript variables: var and let and const by mschuetz on Friday March 06, 2020 @04:59PM (#22507729)
That may be a nice addition to the "do expression" proposal for javascript: https://github.com/tc39/proposal-do-expressions

    let x = do {
        let tmp = f();
        tmp * tmp + 1
    };
Unfortunately it seems like the proposal doesn't get much attention.
Re:JavaScript variables: var and let and const by eyelidlessness on Saturday March 07, 2020 @11:27AM (#22512372)
It would be nice if every JS statement had an expression equivalent.
Re:JavaScript variables: var and let and const by amelius on Friday March 06, 2020 @03:59PM (#22507247)
"let" is what I miss in Python.
Re:JavaScript variables: var and let and const by mschuetz on Friday March 06, 2020 @04:57PM (#22507716)
Along with actual block scopes.
Re:JavaScript variables: var and let and const by Octoth0rpe on Friday March 06, 2020 @04:45PM (#22507625)
My inner pedant really hates this first sentence:

> There are three ways to create variables in a JavaScript application: using var, using let, or using const.

No. There are two ways to create variables (let, var), and _one_ way to create a constant (const).

Re:JavaScript variables: var and let and const by anamexis on Friday March 06, 2020 @05:06PM (#22507780)
Your inner pedant isn't being pedantic enough, then, because the ES spec defines them all as variables.

> 13.3.1 Let and Const Declarations

>

> NOTE let and const declarations define variables that are scoped to the running execution context’s LexicalEnvironment.

http://www.ecma-international.org/ecma-262/6.0/#sec-declarat...

Re:JavaScript variables: var and let and const by winrid on Saturday March 07, 2020 @03:24AM (#22510542)
They're not really constant though, if you wanna be really pedantic. You can modify a const object for example.
Re:JavaScript variables: var and let and const by pfdzm on Saturday March 07, 2020 @03:51AM (#22510665)
It’s constant because it cannot be reassigned - but it is not immutable.
Re:JavaScript variables: var and let and const by winrid on Saturday March 07, 2020 @03:59AM (#22510691)
Right.
Re:JavaScript variables: var and let and const by sunseb on Friday March 06, 2020 @02:00PM (#22506231)
Re:JavaScript variables: var and let and const by eyelidlessness on Friday March 06, 2020 @03:00PM (#22506748)
IMO the article's conclusion is wrong. We should indeed use `const`, and we should indeed use it to communicate. But the thing we should use it to communicate is different than what the article proposes.

We should use `const` to communicate that we don't intend to reassign or mutate the variable. And we should do that by default unless there's a compelling reason to do otherwise.

I know it can't be fully enforced, because JavaScript is designed for mutability of objects by default. But it is an implementation style that is almost always achievable in plain ES6 without too much trouble, and it makes more reliable software that's easier to reason about.

Re:JavaScript variables: var and let and const by _bxg1 on Friday March 06, 2020 @03:38PM (#22507101)
And in TypeScript you can at least pair it with Readonly<...>, though that unfortunately still isn't recursive
Re:JavaScript variables: var and let and const by ht85 on Friday March 06, 2020 @04:36PM (#22507557)
Nice plugin to make sure you never mutate: https://github.com/jonaskello/tslint-immutable/tree/master/t...

You can add a rule based on the name of the variable to allow mutating (e.g. naming it `mutableSomething`)

Re:JavaScript variables: var and let and const by _bxg1 on Friday March 06, 2020 @05:10PM (#22507812)
Interesting, but not really tractable if you have to manually add every single variable to the rules config.
Re:JavaScript variables: var and let and const by chaorace on Friday March 06, 2020 @06:04PM (#22508205)
The plugin allows pattern-based exceptions.

For example, if your rule excluded variables with a "mutable" prefix, you could name your variable mutableSomething and it will be automatically ignored by the linter

Re:JavaScript variables: var and let and const by mgraczyk on Friday March 06, 2020 @02:50PM (#22506653)
I think one important point that Dan and others miss is that `const` enforces a single-assignment style of variable naming that many find preferable. It makes it easier to read and forces people to provide more thoughtful names for their variables. I'm not saying that this behavior is enough to justify using `const` everywhere, but it should be weighed in any judgement about style.
Re:JavaScript variables: var and let and const by hombre_fatal on Friday March 06, 2020 @03:18PM (#22506918)
I'm not sure what either link clarify.

The first link is someone confusing reassignment mutability with value mutability, a common beginner mistake when they read the byline of "const". It's like reading a rant about how { ...obj } only does a shallow clone and thus "doesn't do anything and we all know it" because you can still modify `obj` to modify the new object.

The second link, a tweet, gives no reasoning.

Re:JavaScript variables: var and let and const by allenskd on Friday March 06, 2020 @02:42PM (#22506575)
That's amazing. I was just scratching my head about const when I read the article, "so what's the purpose if I can change the value... but I guess I can't re-assign the variable with a new value .... that's it?"

I still found the article incredibly informative, sadly as someone still stuck working on legacy apps it falls into "...in some near future I'll take advantage of JavaScript new stuff"

Re:JavaScript variables: var and let and const by karatestomp on Friday March 06, 2020 @04:46PM (#22507635)
> That's amazing. I was just scratching my head about const when I read the article, "so what's the purpose if I can change the value... but I guess I can't re-assign the variable with a new value .... that's it?"

If the value is a primitive, you can't change it. If the value's a reference you also can't change that, but of course you can modify whatever that points to.

Is that what's bugging people about this?

Re:JavaScript variables: var and let and const by allenskd on Friday March 06, 2020 @05:58PM (#22508159)
I believe so. I don't make a big issue out of it... but anything carrying the word const I expect it to be fully read-only with no "buts" in between throughout the whole execution of the program. I guess if they used "readonly" as C# it would make more sense?
Re:JavaScript variables: var and let and const by Kaze404 on Friday March 06, 2020 @03:00PM (#22506751)
If you're willing to add a build step to the project, Babel will let you use all the new features and compile down to whatever version you need.
Re:JavaScript variables: var and let and const by allenskd on Friday March 06, 2020 @06:10PM (#22508246)
Thanks, I've never checked out Babel. I will truly suggest that to my lead, seems something we can take advantage of.
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?
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.
Re:JavaScript variables: var and let and const by karatestomp on Friday March 06, 2020 @04:34PM (#22507542)
I read a whole bunch of that tweet thread and got nothing out of it. What's wrong with const? Been using it for quite a while now, seems fine, no trouble. What am I missing?
Re:JavaScript variables: var and let and const by futureproofd on Friday March 06, 2020 @02:11PM (#22506317)
The OP article is common knowledge and is a copy of a copy of a copy. Your first link, on the other hand, is the perfect recipe for my Friday afternoon. Cheers!
Re:JavaScript variables: var and let and const by whowhatwhy on Friday March 06, 2020 @04:10PM (#22507328)
it's also wrong in the first sentence. there are at least 5 ways to define variables in js (edit: hint: globals)
Re:JavaScript variables: var and let and const by the_other_b on Friday March 06, 2020 @02:25PM (#22506431)
Lol that first read is fantastic.

  const doesn't do shit and we all know it
Was a great intro, and absolutely true. Unfortunately I don't think this will catch on, although I agree with the author that it should.
Re:JavaScript variables: var and let and const by k__ on Friday March 06, 2020 @02:35PM (#22506517)
I like the reassignment prevention.
Re:JavaScript variables: var and let and const by irrational on Friday March 06, 2020 @02:32PM (#22506483)
I agree with Dan. I don't use var/const for much the same reason I don't use ==.
Re:JavaScript variables: var and let and const by russellbeattie on Friday March 06, 2020 @04:03PM (#22507270)
Those links are beautiful. It's nice knowing someone else out there has some sense. It makes me feel less alone.

But sadly the pedants won't let this go. The misuse of const is already documented as The Right Way, baked into libraries and live in production in millions of places. Sad but true.

I'd love to do some GitHub sleuthing and find the first few developers out there to publish a project that misused const in their code, so we could tar and feather them. Though obviously being some sort of fad or mass delusion, it wasn't entirely their fault.