1

I have 2 JavaScript functions that return the same object, upon calling both functions one after another, why does the 2nd function return undefined?

function foo1()
{
  return {
      bar: "hello"
  };
}

function foo2()
{
  return
  {
      bar: "hello"
  };
}

console.log(foo1());
console.log(foo2());

// foo1 returns:
// Object {bar: "hello"}
// foo2 returns:
// undefined
Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71

1 Answers1

3

Because automatic semicolon insertion puts a semicolon right after return.

That second function gets turned into:

function foo2() {
  return; // since no value is mentioned, undefined is returned
  {  // This is the start of a block, not an object
    bar: 'hello'; // bar is a line label, not a key in an object.
  }
}

If you want to have your return statement spread over multiple lines, either start the object on the same line (as in foo1), or wrap it in parentheses

function foo2() {
  return (
    {
      bar: 'hello'
    }
  );
}
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • While it's great you want to help, as a steward of SO, you really should vote to close as duplicate rather than provide yet another answer. – random_user_name Oct 25 '18 at 18:08