6

Consider the following case:

function func1() {
  return {
      hello: "world"
  };
}

function func2() {
  return
  {
      hello: "world"
  };
}

console.log(func1());
console.log(func2());

The first function func1() will return the object { hello: "world" } but the second function func2() will return undefined. Why is that? My guess is the returned value needs to be on the same line as the return keyword. What "rule" am I unaware of here?

JLRishe
  • 99,490
  • 19
  • 131
  • 169
Weblurk
  • 6,562
  • 18
  • 64
  • 120
  • [Semicolon insertion.](https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi) – Ilmari Karonen Nov 05 '18 at 12:16

2 Answers2

12

The "rule" is automatic semicolon insertion.

return is a valid statement all on its own, so it is treated as a complete statement. The code starting on the next line is also syntactically valid (although it's not interpreted as an object at all in this case, but rather a code block containing a label and a single "statement" that consists of a string literal). So automatic semicolon insertion kicks in here and the two are treated as separate statements.

The code that starts on the line after the return is simply ignored.

Note that some IDEs and linters can help with this, since you essentially have unreachable code. Here is a screenshot of how VSCode's default syntax highlighting displays the two functions. You can see that the hello: world is shaded a dull color in the second function:

Screenshot of VSCode showing unreachable code.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • This might be helpful too [mozilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return#Automatic_Semicolon_Insertion) – Andrew Bone Nov 05 '18 at 12:20
1

It's because of automatic semicolon insertion. The JS engine is thinking you left out a semicolon on a blank return; statement and "helpfully" inserting it for you.

Other than removing the newline, you can also fix this by putting parentheses around the {..}, the first one on the same line as the return.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34