DEV Community

Sham Gurav
Sham Gurav

Posted on

#26 Guess The Output ???

⭐ Reply with correct answer & Bonus points for explanation ⚡

💡 Correct answer with detailed explanation will be updated in comments after 48 hours.

#26 Guess The Output ???

Code -

function foo1() {
  return {
    bar: 'Hello'
  }
}

function foo2() {
  return
  {
    bar: 'World'
  }
}

console.log(foo1());
console.log(foo2());
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
andrewusher profile image
Andrew Usher
console.log(foo1())
// {bar: 'Hello'}
Enter fullscreen mode Exit fullscreen mode

foo1 returns an object as expected

console.log(foo2())
// undefined
Enter fullscreen mode Exit fullscreen mode

The ASI (automatic semicolon insertion) in JS doing its job here actually causes a bug. The value being returned should begin on the same line, or else foo2 gets compiled down to this:

function foo2() {
  return;
  {
    bar: 'World'
  }
}
Enter fullscreen mode Exit fullscreen mode

This can be fixed by telling JS to start at the next line after the return by using parens

function foo2() {
  return (
  {
    bar: 'World'
  }
  );
}
Enter fullscreen mode Exit fullscreen mode