proposal: let in if parentheses
{
let a = b();
if (a) {
c(a);
}
}
It's possible, but the ability to optionally destructure is what would make this feature worth it - I feel this should wait for pattern matching to be added first, though.
The problem with let, const or var is you can define multiple variable after them, and it's ambiguous which one must be returned from the expression. But like comma expression which would return the last part as a result, the let and const also should return the last assignment as the result so it can be used inside parentheses
(let a = 1, b = 2) === 2
A common type of code in JS is searching for element and do something with them:
let e1 = document.getElementById('id1'); if (e1) this.AppendChild(e);
let e2 = document.getElementById('id2'); if (e2) this.AppendChild(e);
This pattern can really help encapsulation and readability;
if (let e = document.getElementById('id1')) this.AppendChild(e); if (let e = document.getElementById('id2')) this.AppendChild(e);
Anything beyond the last variable shouldn't be returned - anything else
would be exceedingly unexpected. Note that in terms of completions, they
all currently return undefined
when you eval
them, but for if (let ...)
and while (let ...)
, I would expect that it'd work similarly to
sequence expressions.
that's the point, when this is correct:
let a, b; (a = 1, b = 2) === 2;
why not this:
(let a = 1, b = 2) === 2;
and it can be used anywhere other than if parentheses and more important it seems more natural instead of a new feature.
while it's possible to use let keyword in for loop parentheses, it's not possible to use it in if parentheses.
There are two use cases for this:
1- if (let a = b()) a.c();
this can be done using optional chaining which is proposed:
b()?.c();
2- if (let a = b()) c(a);
this or more sophisticated patterns can't be done in any way other than:
let a = b(); if (a) c(a);
beside more line of codes the problem here is a is defined outside of if scope.