Search code examples
javascriptcoding-stylewhitespaceecmascript-5

Understanding ECMAScript implicit semicolons and whitespace parsing


I've seen, very often in fact, this cited as why to use K&R style when writing ECMAScript.

function foo () {
  return
    {
      foo: 1
    }
  ;
}

That doesn't work in ECMAScript or Javascript: implicit-semicolon addition results in the function returning undefined. However I see this all the time too

function bar () {
  var a = "BAR";
  return a
    .toLowerCase()
  ;
}

And, I'm wondering why implicit semicolons doesn't result in that returning "BAR", why does bar get returned there?


Solution

  • Because the syntax doesn't work with an implicit semicolon at the end of the line.

    If you add the semicolon:

    function bar () {
      var a = "BAR";
      return a;
        .toLowerCase()
      ;
    }
    

    you would get a syntax error on the next line.