Skip to content Skip to sidebar Skip to footer

Why Does The Value Returned Should Be On The Same Line As The Return Statement In Javascript?

The following doesn't work as I would expect it to: function test() { // Returns undefined, even though I thought it would return 1 return 1; } Apparently, the value should

Solution 1:

It's explicitly part of the language spec. If it were not, there would still be return issues:

if (something())  return
counter = counter + 1;

Without the semicolon insertion rule, that missing semicolon would trigger behavior that's (I'd argue) just as bizarre as what happens now with return statements split across a newline.

Solution 2:

Javascript automatically inserts a semicolon after the "return" statement if the return expression is not on the same line.

JavaScript has a mechanism that tries to correct faulty programs by automatically inserting semicolons. Do not depend on this. It can mask more serious errors. It sometimes inserts semicolons in places where they are not welcome. Consider the consequences of semicolon insertion on the return statement. If a return statement returns a value, that value expression must begin on the same line as the return:

return
{
   status: true
};

This appears to return an object containing a status member. Unfortunately, semicolon insertion turns it into a statement that returns undefined. There is no warning that semicolon insertion caused the misinterpretation of the program. The problem can be avoided if the { is placed at the end of the previous line and not at the beginning of the next line:

return {
   status: true
};

Quoted from this post, citing JavaScript: The Good Parts by Douglas Crockford. Copyright 2008 Yahoo! Inc., 978-0-596-51774-8.

Solution 3:

JavaScript will insert a semi-colon in certain cases to try to make an otherwise invalid program into a valid one. In particular, a return statement is an example of what's called a "restricted production" -- you aren't allowed to have a line break after return before the value, so it gets transformed into return; and the following value becomes a separate statement.

In the case of

foo
=
1

this is not a restricted production, and furthermore neither = or 1 are illegal tokens in that position, so there's no attempt to insert a semi-colon at the end of the preceding line.

Solution 4:

JavaScript uses semicolon insertion! For every line you forgot to close it with a semicolon JS will insert it automatically! In this case:

return// auto semicolon insertion
{ // that's fine1; // yey here's one
} // ok, np// bye bye

This means in JavaScript the use of { opening bracket is not, like in other languages, by developer's choice. You have to follow the rules:

return {
    1;
}

Post a Comment for "Why Does The Value Returned Should Be On The Same Line As The Return Statement In Javascript?"