Javascript object return syntax

Asked

Viewed 144 times

5

Using the Chrome console I used the following code (valid):

function foo()
{
    return {
        prop: "some value"
    };
}

when the syntax style is changed is no longer valid ({ played to next line):

function foo()
{
    return 
    {
        prop: "some value"
    };
}

teste no Chrome

This is a Javascript syntax rule or a bug implementation of browsers? I tested this in Internet Explorer also (same behavior).

  • Sure there’s nothing else in the code that might be giving you a false positive? Because here, in the most recent Chrome, it worked, quietly, that is, Alert() showed value.

  • sure, I’m just testing the basics, your code is the first version I posted, check it out: http://jsfiddle.net/hfHFk/1/

2 answers

3


The syntax is:

Return [ Expression ];

And it says "Expression":

To Expression return. If omitted, Undefined will be the return.

Source MDN

This implies that the expression, variable, object, etc are on the same line as the code. If you change lines the interpreter will think that you have a return isolated and makes return of undefined.

  • 2

    If omitted, undefined is returned instead. Thanks @Sergio, I think I got my question

2

Complementing the @Sergio response, it is necessary to put in the same line because the semicolon, in Javascript, is optional.

When you do:

return 
{
    prop: "some value"
};

The interpreter understands how:

return;
{
    prop: "some value"
};
  • 1

    Thanks @Beet, I was thinking about it yesterday... is one of the principles I had forgotten hehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.