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

  • A+
Category:Languages

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?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: