1

This code produces no errors:

function func() {
  xmlhttp.onreadystatechange = function stateChanged() {
    if (xmlhttp.readyState == 4) {
      /* stuff happens herer */
    }
  }
  func2(xmlhttp)
}

If I put all put all the code on a single line I get SyntaxError: unexpected token: identifier

function func() { xmlhttp.onreadystatechange = function stateChanged() { if (xmlhttp.readyState == 4) { /* stuff happens herer */ } } func2(xmlhttp) }

What difference does a single line make?

Daniel Williams
  • 1,947
  • 3
  • 23
  • 40
  • 1
    Semicolons. ASI (Automatic Semicolon Insertion), that lets them be optional in many cases, [does often depend on the presence of `LineTerminator`s](https://stackoverflow.com/a/2846368) or line breaks. – Jonathan Lonowski Sep 21 '18 at 03:29
  • 1
    but why minify manually when there are so many tools to handle that ... – Slai Sep 21 '18 at 03:38

1 Answers1

1

It's amazing what a difference having explicit statement separators (i.e. a semi-colon ;) will do for you instead of depending on implicit ones (i.e. carriage-return). Try this:

function func() { xmlhttp.onreadystatechange = function stateChanged() { if (xmlhttp.readyState == 4) { /* stuff happens herer */ } }; func2(xmlhttp) }

The issue is that when you do your assignment ( xmlhttp.onreadystatechange = ) the parser can't tell where the assignment should end without the author explicitly saying so.

Tibrogargan
  • 3,599
  • 3
  • 16
  • 33
  • I see, so you're saying that JS assumes, if no semi-colon is found, a line break is a good enough guess that it's finished? I didn't realize that a `}` could need a closing semi-colon. – Daniel Williams Sep 21 '18 at 03:34
  • Yes. The answer that @JonathanLonowski linked gives a more complete answer, including references to the spec. Some people will terminate every line with a semi-colon simply to eliminate the possibility of running into this issue. – Tibrogargan Sep 21 '18 at 03:37
  • 1
    What minifier are you using? All good minifiers can handle ASI properly. – Lazar Ljubenović Sep 21 '18 at 03:38
  • I'm writing my own :/ – Daniel Williams Sep 21 '18 at 03:40