1

Hi have the following JavaScript function. When I call it, it returns undefined. I would expect it to return an object. Why does it return undefined?

function someFunction() {
    return
    {
      name: 'Mary'
    };
  }

For example:

https://jsfiddle.net/richardmarais/Lwpygd17/1/

Thanks

Richard
  • 8,193
  • 28
  • 107
  • 228
  • 1
    You should not add a break line after return. It returns undefined because javascript interprets your code as `return; { ... } ` . So it will return undefined. Even in the jsfiddle you shared you can see an error on that line. ( the red dot ) . saying `line break error` – Mihai T Sep 10 '19 at 08:00

2 Answers2

3

Automatic Semicolon Insertion

The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.

In JavaScript return followed by nothing (in the same line) is evaluated as return;

function someFunction() {
  console.log('function called');
  return{
    name: 'Mary'
  };
}

var o = someFunction();
console.log(o);
Mamun
  • 66,969
  • 9
  • 47
  • 59
3

In javascript the ; is optional.

Therefore, your browser interpretes your code like this :

function someFunction() {
    return;   // It adds automatically a semi colon here
    {
      name: 'Mary'
    };
  }

So, if you want it to work, you need to do this

function someFunction() {
    return{
      name: 'Mary'
    };
  }
Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
  • Really the semicolon _isn't_ optional. If you miss them out the they are inserted by the ASI routine which is an _error correction routine_. – Andy Sep 10 '19 at 08:06
  • @Andy Don't you think it might depend on your point of view? From a dev point of view, you don't really need semicolons, do you? If you look at JS grammar, you will see a dev does not need to add a semicolon everywhere. (I won't say it's a good idea) – Deblaton Jean-Philippe Sep 10 '19 at 08:13