Proposal: anaphoric if and while syntax

Danielle McLean gopsychonauts at gmail.com
Sat Oct 1 05:50:34 UTC 2016


On 14 September 2016 at 17:58:24, Viktor Kronvall
(viktor.kronvall at gmail.com(mailto:viktor.kronvall at gmail.com)) wrote:

> Does this really need new semantic interpretation of the syntax? Using the `Array.prototype` methods `.forEach` and `.map` already mitigates this problem as far as I can tell by having a different bound variable (argument in this case) for each call.
>
> I agree that the behavior may be non-intuitive if you have a background coming from Java or C++ but the implications would be quite far-reaching and the backward compatibility with previous versions would be difficult to handle. Wouldn't this require a new 'use strict'-like mode?

No, adding anaphoric if as I have described it will require neither
new semantic interpretation of the syntax nor a new strictness
directive. Currently, it is a syntax error to write a variable
declaration within an `if` or `while` condition, so there is no valid
code which contains the proposed syntax.

Also note that under this proposal, declarations made using the `var`
keyword would still be hoisted to function scope, *not* scoped to the
body associated with the condition - i.e., there would be no semantic
difference whatsoever between the following two snippets:

    if (var stuff = some.cool(expression)) doThings(stuff);
    // equivalent to
    var stuff;
    if (stuff = some.cool(expression)) doThings(stuff);

Only declarations made with the newer `let` and `const` keywords,
which are never hoisted to function scope anyway, would be narrowly
scoped to the condition and its body.

    if (let stuff = expr) doThings(stuff);
    // equivalent to
    {
      let stuff = expr;
      if (stuff) doThings(stuff);
    }

(An aside: as the last example demonstrates, the `if` or `while`
statement body should not need braces to isolate the scope in this
way. This is consistent with the current behaviour for declarations in
loops.)


More information about the es-discuss mailing list