0

The following function works and does its intended job - returns the desired value as specified.

function returnValue() {
    return( 
          "value");
}

Just the return value is split into a new line.


If the pair of parentheses is dropped as follows then, it returns undefined.

function returnValue() {
    return 
         "value";
}

The IDE I'm using issues a warning as follows.

Code has no side effects

It seems like "value" is not part of the return statement itself.

Why do they both behave differently?

Tiny
  • 24,933
  • 92
  • 299
  • 571

4 Answers4

4

Because in Javascript, a statement can be terminated by a newline instead of a semicolon. The semicolon is essentially inserted automatically, but only where the result can be a full statement.

return; is valid on its own, but then your function returns nothing and your "value"; has no side-effects.

On the other hand, your first example simply cannot be parsed this way because the line ends in the middle of a parenthesis.

These rules are described in §7.9.1 in the ECMA-262 standard document.

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
3

Automatic Semicolon Insertion is the cause. When the expression to return starts on a separate line to the return keyword, a semicolon is inserted after the return statement. Semicolons are optional in many cases but this is not one of them

So

function returnValue() {
    return 
         "value";
}

ends up becoming/being interpreted as

function returnValue() {
    return; // <- semicolon inserted here
         "value";
}

which results in undefined being returned. One way to fix this is to start the value to return on the same line as return.

There are rules for when automatic semicolon insertion happens, summarized as

The resulting practical advice to ECMAScript programmers is:

  1. A postfix ++ or -- operator should appear on the same line as its operand.
  2. An Expression in a return or throw statement should start on the same line as the return or throw token.
  3. A label in a break or continue statement should be on the same line as the break or continue token.
Russ Cam
  • 117,566
  • 29
  • 193
  • 253
2

Javascript automatically inserts a semicolon after return.

Read more: What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Community
  • 1
  • 1
kapa
  • 72,859
  • 20
  • 152
  • 173
2

That's because JavaScript automatically adds a semicolon to the end of the return line, so in the second example, it's essentially as if it said just return;.

José Tomás Tocino
  • 8,637
  • 5
  • 40
  • 71