function foo1() {
return {
bar: "hello"
};
}
function foo2() {
return
{
bar: "hello"
};
}
console.log(foo1());
console.log(foo2());
Can I get an explanation why the two functions print out different results even though the code looks the same?
Automatic semicolon insertion
Quoting the specification,
When a
continue
,break
,return
,throw
, oryield
token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after thecontinue
,break
,return
,throw
, oryield
token.
So the code will become like this
function foo2() {
return; // Note the `;` after `return`
{
bar: "hello"
};
}
The return
statement terminates and then there is an object after that, which is basically unreachable code. Since the return
statement doesn't return anything explicitly, undefined
will be returned.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments