Logic
JavaScript
13 January 2024
1function foo1() 2 { 3 return { 4 bar: "hello" 5 }; 6 }
In this function, the return statement is followed by an object literal { bar: "hello" }. The object literal is a valid expression and is considered part of the return statement. The function will return an object with a property bar set to the string "hello".
1function foo2() 2 { 3 return 4 { 5 bar: "hello" 6 }; 7 }
In this function, it might seem like the return statement is followed by an object literal, similar to foo1. However, due to automatic semicolon insertion in JavaScript, the actual interpretation is different.
The JavaScript engine inserts a semicolon after the return statement, treating it as if it were written like this:
1function foo2() { 2 return; 3 { 4 bar: "hello" 5 }; 6}
As a result, the function foo2 will return undefined, and the object literal { bar: "hello" } is treated as a separate code block that is not associated with the return statement.