0

I have seen this trick question online without any answer or description. Not sure what's going on here:

function identity() {
    var name = 'Jack';
    alert(name);
    return
    name
};
var who = identity();
alert(who)

This snipped outputs, jack & then undefined, why?

RuntimeException
  • 1,135
  • 2
  • 11
  • 25

2 Answers2

7

Change this

return
name

to this:

return name;

The return statement is one of the few places where javascript does not like whitespace. EDIT. What's happening in the original is the browser inserts a semicolon after the return statement, like this

return;
name // this gets ignored

So the return value is undefined.TehShrike links to a very good document explaining the exact rules ECMAAScript environments must follow when ignoring whitespace/line breaks and when semicolons must be inserted.

The ECMAScript standard says this (among other things)

Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.

  • 1
    Specifically, Javascript's [automatic semicolon insertion](http://inimino.org/~inimino/blog/javascript_semicolons) adds a semicolon to the end of the `return` line. – TehShrike Sep 19 '13 at 15:34
  • 1
    You might also want to answer the actual question (why it returns `undefined`). – JJJ Sep 19 '13 at 15:35
  • 2
    This is a lot of upvotes for an answer talking past the question. – Evan Davis Sep 19 '13 at 15:35
  • That's why we are encouraged to improve our answers. :) –  Sep 19 '13 at 15:39
1

identity is a function. who then declares a new instance of that, which we can tell from the func that it will create a local variable name and assign jack to it, then alert.

The function then looks like it return nothing (although name is on the next line, so I'd imagine you want to return that, change to return name;).

tymeJV
  • 103,943
  • 14
  • 161
  • 157