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?
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.
5. What will happen if a return statement does not have an associated expression? Explanation: A function without a return statement will return a default value. If the return statement does not have an associated expression then it returns an undefined value.
No. Weak operators in JS make it seem like the might return the same thing, but they return objects of different types. false != null on jsbin.com and jsfiddle.net.
Yes, return stops execution and exits the function. return always** exits its function immediately, with no further execution if it's inside a for loop.
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 code that starts on the line after the return
is simply ignored.
Note that some IDEs and linters can help with this, since you essentially have unreachable code. Here is a screenshot of how VSCode's default syntax highlighting displays the two functions. You can see that the hello: world
is shaded a dull color in the second function:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With