2

I just started working a bit with javascript but quickly got stuck with a - in my eyes - quite simple task of returning an object literal.

The code I currently have looks like this

function wrapInObject(x)
{
    return
    {
        y: x
    };
}
console.log(wrapInObject('someValue'));  

but instead of writing the object literal to the console it prints undefined - I tried calling the function with numbers or other object literals but nothing helped.

Thanks for any help!

tengobash
  • 317
  • 1
  • 9

3 Answers3

3

This is due to a process known as automatic semicolon insertion and is quite often the source of confusion for new devs with a C# background or other languages where placing the opening brace on a new line is common practice.

Essentially what happens is that an implicit semicolon is placed right after your return statement so that it returns undefined and your object literal is never 'reached'.

To fix it just move the opening brace to the end of the return like so

function wrapInObject(x)
{
    return { 
        y: x 
    };
}
DAXaholic
  • 28,212
  • 5
  • 58
  • 67
0

Because of automatic semicolon insertion

function wrapInObject(x)
{
    return
    {
        y: x
    };
}
console.log(wrapInObject('someValue'));

gets converted to

function wrapInObject(x)
{
    return ; // semicolon is added
    {
        y: x
    };
}
console.log(wrapInObject('someValue'));  

Hence you get undefined.

Clyde Lobo
  • 8,747
  • 6
  • 34
  • 58
0

This is because of semicolon auto-insertion adding a line break after the return statement makes the js engine parse that line as if there was a semicolon. Move the opening bracket to the same line as the return statement.

Another StackOverflow entry about semicolon auto-insertion

Community
  • 1
  • 1
Nicholas
  • 2,538
  • 1
  • 17
  • 18