Search code examples
javascriptminify

Removing Javascript line breaks causing token identifier error


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?


Solution

  • 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.