JavaScript’s return statement gotcha

11 / Feb / 2014 by Manvendra Singh 2 comments

Hi everyone,

This blog is about how JavaScript parses your script (source code) when it encounters return statement. We can write code using any one style of following two:

Style 1:

[sourcecode language=”java”]
function func() {
return 6;
}
[/sourcecode]

and

Style 2:

[sourcecode language=”java”]
function func()
{
return 6;
}
[/sourcecode]

And people usually say that this is the matter of personal preference. But watch out! Here’s the catch. You can’t always put opening curly brace on next line just after return statement. For example, if you want to return an object from the function then the following code will not work:

[sourcecode language=”java”]
function func() {
return
{
"key": "value"
};
}
[/sourcecode]

It’ll throw SyntaxError. The reason is how the JavaScript interpret its source code file. As we all know semicolon at line end is optional, and in this optional case JavaScript parser tries to break the physical line to logical line using new line character, and thus problem begins. So the correct way is as follows:

either this:

[sourcecode language=”java”]
function func() {
return {
"key": "value"
};
}
[/sourcecode]

or like this:

[sourcecode language=”java”]
function func()
{
return {
"key": "value"
};
}
[/sourcecode]

So folks, never put opening curly brace on next line just after return statement, whether you like it or not!

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Eran

    Good post. Note that the same applies to any value returned from the return statement. For example
    function foo()
    {
    return
    42;
    }

    will not work as expected. Obviously it makes little sense to break the above, but when returning a complex expression it might be tempting to start one line down.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *