Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the { position affects this Javascript code?

I spent a fair bit of time on this Javascript issue (you can tell I am a JS noob):

Take some well written Javascript code like this example of the Revealing Module Pattern:

Running it works fine. Then move the "{" to the next line (as a C# developer I set up all my environments to put curly braces on new lines) and run it again.

  return   
  {
    someMethod : myMethod,
    someOtherMethod : myOtherMethod
  };

It now gets quite a few JS errors around "13 Line breaking error 'return'." and "Uncaught SyntaxError: Unexpected token : " in Chrome Debugger.

My question is, how can something syntactically affect the Javascript like this?

I have set it up here in JSFiddle (to get it to work, move the { after "return" back on to the same line)

like image 694
Rodney Avatar asked Mar 04 '14 23:03

Rodney


People also ask

Does position of script tag matter?

Yes, it does affect the performance of the web page.

What is the best place to put your JavaScript code?

You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.

Why is JavaScript placed at the bottom?

When you place your JavaScript at the bottom of your HTML body, it gives the HTML time to load before any of the JavaScript loads, which can prevent errors, and speed up website response time.


3 Answers

One of JavaScript’s worst features is Automatic Semicolon Insertion.

return; // a semicolon is implicitly inserted here

And this part is almost valid JavaScript, but not quite, so you get a syntax error:

{
    someMethod : myMethod,
    someOtherMethod : myOtherMethod
};

If you had tried to do this:

return
    [ 1, 2, 3,
      4, 5, 6,
      7, 8, 9 ];

it would have just returned undefined all the time, and that would have been bad. ASI sucks, but we’re stuck with it now, especially since semicolonless code has become a fad.

What does this do?

return a
     + b
     + c;

This?

return e
     / f /g;

Okay, okay, maybe that one’s a bit contrived, and maybe this isn’t entirely topical. But ASI is bad. I hope everyone gets that.

like image 75
Ry- Avatar answered Oct 31 '22 04:10

Ry-


Because the ECMA standard section 12.9 states you can't have a new line between the return keyword and its expression.

    ReturnStatement :
       return ;
       return [no LineTerminator here] Expression ;
like image 36
Phillip Kinkade Avatar answered Oct 31 '22 04:10

Phillip Kinkade


Javascript does something called Automatic semi-colon insertion which I believe is what is affecting your results here. Basically, it sees the return statement with nothing after on the line, and thinks that's the end of the line and returns, ending the function.

like image 45
Will P. Avatar answered Oct 31 '22 04:10

Will P.