JavaScript variables: var and let and const
prestonlamb.com
prestonlamb.com
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 :)
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)
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.
I suppose when I get to use voice recognition for coding, there will also be less confusion.
Are you being charged by the character or something?
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?
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.
Gross.
Transpilation is "best effort" and involves some tradeoffs.
You don't need to read other articles on this subject, it's that simple.
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.
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.
Sure, you’ll often need to split declaration from assignment with let in that case, but that's not a bad thing, IME.
try {
const { attribute1, attribute2 } = getObject()
} catch () {}
attribute1 // undefined
How would you solve that?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.
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 let attribute1, attribute2;
try {
({attribute1, attribute2} = getObject())
} catch (e) {}So parenthesis are the trick, thanks!
const outer = (() => {
try {
...
return ...
} catch (error) {
...
}
})() let x = do {
let tmp = f();
tmp * tmp + 1
};
Unfortunately it seems like the proposal doesn't get much attention.> 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).
> 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...
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.
You can add a rule based on the name of the variable to allow mutating (e.g. naming it `mutableSomething`)
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
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.
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"
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?
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.
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.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
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.
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.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.