Proposal: anaphoric if and while syntax

Danielle McLean gopsychonauts at
Tue Sep 13 00:32:06 UTC 2016

In current ECMAScript, it is legal to place a variable declaration inside the
initialiser of a `for` loop, as well as to declare the variable used by a
`` or `for...of` loop within the declaring expression:

    for (let i = 0; i < 5; ++i) console.log(i);
    for (let item of collection) process(item);

When this syntax is used with `let` or `const`, the resulting variable is
scoped to the loop and is not visible to the rest of the surrounding block.

I propose that this syntax be extended, making it legal to place a variable
declaration within the condition of an `if` or `while` statement. Any truthy
value will cause the `if` block to run or `while` loop to repeat, as usual -
the advantage is that the particular truthy value is bound to a variable and
can be used inside the conditional block. For example, here is the situation
that prompted my writing this proposal:

    if (const oldValue = _.get(object, 'some.long.path')) {
      object.some.long.path = transform(oldValue);

As with the existing behaviour of declarations inside `for`, variables declared
using `let` or `const` would be scoped to the individual `if` or `while`
statement, rather than the containing block. In other words, the above syntax
would be equivalent to the following currently-valid form I ended up writing:

      const oldValue = _.get(object, 'some.long.path');
      if (oldValue) object.some.long.path = transform(oldValue);

Another use case which C aficianados might recognise:

    while (const c = getchar()) {

This syntax is already legal in C++, although not in C - in general this
support is known as "anaphoric if", as it allows the body of the statement to
refer back to the condition value. It's especially helpful in languages with
truthiness, which ECMAScript has, as it allows access to the *specific* truthy
value without further finagling.


More information about the es-discuss mailing list