3

Since ES6, a new case has been added for rule 1 of automatic semicolon insertion:

The previous token is ) and the inserted semicolon would then be parsed as the terminating semicolon of a do-while statement (13.7.2).

This allows one to avoid line termination and write ugly code such as:

do {} while (false) var a = 42

What is the rationale behind this rule? Some useful use-case?

lledr
  • 537
  • 1
  • 3
  • 12
  • Minifiers are the only thing I can think of. Also, I can't really see a reason where you'd want `do {} while (false) var a = 42` to be parsed as anything other than a `do..while` loop followed by a variable declaration. – VLAZ Apr 26 '20 at 09:47
  • I think that's just because of the rule for `}`, and the `do..while` restriction is needed only because `)` doesn't necessarily end a statement unless it is the part of a `do..while`, where nothing else is permitted in the same statement after the `)` – FZs Apr 26 '20 at 09:48

1 Answers1

4

I'm pretty sure that "case" added in ES2015 is only there to standardize rules which browsers had already implemented in order to be compatible with terribly-written (or weirdly minified) scripts. It wasn't exactly a new feature, so much as it was a tweak of the specification to be in line with what browsers were doing already.

For example, your snippet runs in IE11, which was released in 2013:

do {} while (false) var a = 42;
console.log('no parse errors');
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you @CertainPerformance, I had the same question. Would you know why browsers allowed code like that in the first place instead of letting it syntax error as in `var x = 1 var y = 2`? The use case cited by [these](https://bugzilla.mozilla.org/show_bug.cgi?id=238945#c2) [threads](https://github.com/tc39/ecma262/issues/684) is `do {} while (false) return;`. But when is something like this useful? – user51462 Nov 05 '21 at 06:54