2
(function(){
  function sayHello(){
    var name = "Hi John";
    return
    {
      fullName: name
    }
  } 

  console.log(sayHello().fullName);
})();

The console will output

Uncaught TypeError: Cannot read property 'fullName' of undefined

I read this question from an interview exercise book,and I cannot understand the reason behind this, anyone could help me?

pyy
  • 915
  • 3
  • 9
  • 25

2 Answers2

4

The problem here is automatic semicolon insertion after return statement.

You can't place code on a new line after return statement because javascript will automatically place ; on the same line with return statement and the rest of the code is ignored.

(function(){
  function sayHello() {
    var name = "Hi John";
    return { fullName: name };
  }

  console.log(sayHello().fullName);
})();
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
1

Because of Automatic Semicolon Insertion the parser will read your code as:

return  ; // <---
{
  fullName: name
}

So it returns actually nothing, which is undefined in javascript.

By the way: The following object literal also gets invalid as it is not an expression anymore but a statement (a block statement) and then the key-value-pair doesn't make sense.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151