Why the same type of return, but the result is the difference

I have two functions of the same return type in a java script, but the return type is the difference. Disabled id code used below

function foo1() { return { bar: "hello" }; } function foo2() { return { bar: "hello" }; } 

function call.

 console.log("foo1 returns:"); console.log(foo1()); console.log("foo2 returns:"); console.log(foo2()); 

Print the result ....

 foo1 returns: Object {bar: "hello"} foo2 returns: undefined 
+5
source share
3 answers

Its automatic semicolon insertion. The rest of the code is never reached.

 function foo2() { return // get a automatic semicolon insert here { bar: "hello" }; } 

Please see: Warning: code not available after return

+4
source

This is because JavaScript interprets

 return { bar: "hello" }; 

like return , followed by the creation of a block (which is ignored at runtime). Not how to "return an object." And I really don't know why JavaScript developers made this decision.

In any case, ASI inserts ; after return , which leads to the equivalent code:

 return; { bar: "hello" }; 

The new line after return is the culprit. Do not use it if you want to return something.

+4
source

Free javascript that you do without a semicolon but puts an automatic semicolon, so you get undefined Refer to this question

 function foo1() { return { bar: "hello" }; } function foo2() { return{ bar: "hello" }; } console.log("foo1 returns:"); console.log(foo1()); console.log("foo2 returns:"); console.log(foo2()); 
0
source

All Articles