5

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
  • 95,368
  • 17
  • 122
  • 158
Weblurk
  • 6,279
  • 16
  • 58
  • 109
  • [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

11

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 object that starts on the line after it is simply ignored.

JLRishe
  • 95,368
  • 17
  • 122
  • 158
  • 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
  • 16,251
  • 2
  • 19
  • 31