0

I am trying some simple javascript and what I discovered is quite amazing if you ask me, I was wondering why javascript behaves like this. So I have a simple inline function that defines two inner functions: task 1 and task2, and has a return object with two properties: job1 and job2, where job1 points to task1 and job2 points to task2. I get an error like:

Uncaught SyntaxError: Unexpected token :

and the amazing part is that if I move the curly brace immediately after the return statement (see comment in code), the script actually works and prompts an alert "1" as expected. Why does it matter if I put the curly brace immediately after return or on the next line?

<!DOCTYPE html>
<html>

  <head>
    <script data-require="angular.js@*" data-semver="4.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/2.0.0-beta.17/angular2.min.js"></script>

  </head>

  <body>
    <h1>Hello!</h1>
  </body>

</html>
<script type="text/javascript">

var x = function()
{
    var task1 = function() { alert("1"); }
    var task2 = function() { alert("2"); }

    return 
    { ///////////// move this on the previous line right after return
        job1: task1,
        job2: task2
    };
}

x().job1();

</script>

I always thought that in javascript this:

var x = function() {
//content
}

is equivalent to this:

var x = function() 
{
//content
}

but obviously not in the case I mentioned first. Why?

Sami
  • 393
  • 8
  • 22
  • 2
    Possible duplicate of [Javascript function fails to return object when there is a line-break between the return statement and the object?](https://stackoverflow.com/questions/18221963/javascript-function-fails-to-return-object-when-there-is-a-line-break-between-th) – freedomn-m Dec 03 '17 at 16:28
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return#Automatic_Semicolon_Insertion – A. Wolff Dec 03 '17 at 16:29
  • 1
    further reading https://stackoverflow.com/questions/8528557/why-doesnt-a-javascript-return-statement-work-when-the-return-value-is-on-a-new – semuzaboi Dec 03 '17 at 16:31
  • 1
    Please see this [thread](https://stackoverflow.com/questions/3960518/javascript-formatting-must-braces-be-on-the-same-line-as-the-if-function-etc-ke) on the StackOverflow forum :) – Tom Dec 03 '17 at 16:34

1 Answers1

3

Why does it matter if I put the curly brace immediately after return or on the next line?

Because semi-colons are optional in javascript. The parser does some "magic" to determine where the end of statement is and sees return<newline> as the equivalent of return;.

freedomn-m
  • 27,664
  • 8
  • 35
  • 57