0

For example

function a(){
    return {
        testing:1
    };
}

function b(){
    return 
    {
        testing:1
    };
}

In the above code the function a() returns an object of {testing:1}, but the function b() returns the value of undefined. What is the reason behind this behaviour?

Is it because the return value starts in the second line?

jarmod
  • 71,565
  • 16
  • 115
  • 122
Ashokkumar
  • 327
  • 4
  • 16

4 Answers4

1

Yes, is happening because when the interpreter runs the b function an see the return expression an anything near, it return undefined.

You have this:

function b(){
    return 
    {
        testing:1
    };
}

And the code is interpreted:

function b(){
    return;   //Returning undefined 
    {
        testing:1
    };
}
michaelitoh
  • 2,317
  • 14
  • 26
1

The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.

To avoid this problem (to prevent ASI), you could use parentheses:

return ( //return statement. );

function a(){
return ({
testing:1
});
}

function b(){
return( 
{
testing:1
});
}
console.log(a());
console.log(b());
NullPointer
  • 7,094
  • 5
  • 27
  • 41
1

Javascript can be funky at times, but just having return at the end of a function returns, just returns nothing/null/undefined. I think your case the space between return and { is causing it to return anyway, despite the array there.

Like your function a(), have it typed like this:

function a(){
    return {
    testing:1
    };
}

function b(){
    return {
    testing:1
    };
}
Zac
  • 1,719
  • 3
  • 27
  • 48
0

Indeed. The return statement is affected by automatic semicolon insertion and no line terminator is allowed between the return keyword and the expression. In fact your second function can be rewritten as

function b() {
    return;
    {testing:1};
}
Vasyl Moskalov
  • 4,242
  • 3
  • 20
  • 28