Proposal - `for .. else ...` (also `while ... else ...`) statement

A tool that is dangerous 99% of the time, is dangerous :-)

What is that link? It doesn't have an href.

Indeed, I can found this in jquery-3.7.1.min.js:

show/hide code
map:function(e,t,n){var r,i,o=0,a=[];if(c(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&a.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&a.push(i);return g(a)}

prettified:

map: function (e, t, n) {
  var r,
    i,
    o = 0,
    a = [];
  if (c(e))
    for (r = e.length; o < r; o++)
      null != (i = t(e[o], o, n)) && a.push(i);
  else for (o in e) null != (i = t(e[o], o, n)) && a.push(i);
  return g(a);
},

If this script stops working, a large number of sites are likely to be affected.

react-dom.production.min.js is also affected:

if(a.alternate)for(;b.return;)b=b.return;else{
1 Like

It’ll never stop being valid, but that doesn’t mean it’s safe for a human to write that code.

So what about then? It means "then finished" (without breaking).
It seems like this is a common case:

for (let i = 0; i < array.length; i++) {
    if (condition) {
        array.splice(i, 1); // doing something with the found element
        break;
    }
}
then console.log('Not found');

I need this too. It allows to do something if the cycle was fully finished.

Honestly, the curly braces "issue" IMHO is only an issue to the degree it conflicts with if/else (as this is heavily relied on in the wild, for minified and non-minified code alike).

The easiest fix would be binding else to an outer if before an inner for first, through a cover grammar. That would also force outer braces if you want something like if (cond) { for (...) else ... }. And honestly, you'd want braces in such situations anyways, just for readability reasons.

So instead of just augmenting for statements to include for (...) else ..., you'd split statements into three productions:

  • PrimaryStatement: includes all current statements except ForStatement and ForStatementAllowElse
  • ConditionedBody: PrimaryStatement | ForStatement
  • Statement: PrimaryStatement | ForStatementAllowElse

Then, you'd use ConditionedBody for if consequent bodies and Statement everywhere else. This could also be easily extend this to include while ... else as well.

1 Like

Yes, if really deserves to have more high priority.
But using then instead of if, I think, is also good. It means "then/if fully done".