2

I’m still trying to get to grips with function definitions: am I correct in saying that this returns a type of undefined?

function foo() {
  return
  {
    car: 'Audi'
  };
}
Horai Nuri
  • 5,358
  • 16
  • 75
  • 127
rijoy
  • 23
  • 2

2 Answers2

6

It returns undefined, because of Automatic Semicolon Insertion. This is one of the major ASI hazards. Having a line break after return makes it get treated as return;. So your code ends up being:

function foo() {
  return;         // <=== Function returns here
  {               // \
    car: 'Audi'   //  > This is a freestanding block with a labelled statement which is the expression 'Audi'
  };              // /
}

Remove the line break and it returns an object:

function foo() {
  return {
    car: 'Audi'
  };
}

This is one reason that putting the opening { on things is standard practice in JavaScript, even more so than other C-like languages.

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

Javascript assumes return to be return;, if you want to return any value it should be in the same line as return.

If you are getting undefined when you execute this function foo, that's because the function is returning at return itself, to get the object as return value, modify your function to be

function foo() {
  return {
    car: 'Audi'
  };
}
Akash Shrivastava
  • 1,365
  • 8
  • 16