0

I have written 2 javascript function but they are not working as same.

console.log(func2()); is undefined. Can anyone tell me why and how to solve this?

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

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

console.log(func1());
console.log(func2());
Ruhul Amin
  • 1,751
  • 15
  • 18

2 Answers2

7

It's because of automatic semicolon insertion. Never put a newline after return and prior to what you want to return, it's treated as though it terminates the return statement (e.g., a ; is inserted after return), and your function ends up effectively returning undefined.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

I know this one. It's semicolon insertion. func2 is translated to

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

And return undefine.

vothaison
  • 1,646
  • 15
  • 15