Proposal: if variable initialization

Waldemar Horwat waldemar at google.com
Sat Apr 7 00:52:19 UTC 2018


On 03/22/2018 11:21 PM, Naveen Chawla wrote:
> I'm still not seeing a compelling case for not allowing `const` / `let` declarations to be evaluated as expressions. Or I've missed it.

Yes, I think there is a compelling case for not allowing `const` / `let` declarations to be evaluated as expressions.

> As was noted,
> 
> `if(x = 5)` is already allowed.
> 
> Is `if(const x = 5)` really that much of a stretch?

That's fine in this case, and I happily use this construct in C++.

But that's *very* different from allowing `const` / `let` declarations anyplace you allow an expression.

> To answer a concern about a function call like `myFunction(const x = 7)`, of course the scope of `x` would be where it is declared.

And here we come the problem: the scope.

> It can't be anywhere else (like inside myFunction or something).

We wouldn't want to repeat the var hoisting problems, so the scope of a general subexpression declaration would need to be the subexpression in which it's contained and not some outer context.  If you don't do that, you'll eventually run into the same problems as with var.

However, that's not what the current uses of such declarations do.  For example,

for (var i = expr; ...) {...}

scopes i to the body of the loop, and you get a new i binding for each iteration, which is important for lambda capture, even though expr is evaluated only once.  Subexpression scoping would be incompatible with that.

As such, we can reasonably allow `const` / `let` declarations in other specific contexts such as at the top level of if statement condition expressions, but not in subexpressions in general.

     Waldemar


More information about the es-discuss mailing list