Why does a return statement on a new line not return any value?

Viewed 947

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?

2 Answers

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.

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.

Related