0

Here's a minimal working example that I have:

function foo () {
    return
        1;
}

function bar () {
    return 1;
}
console.log(foo()); //Undefined
console.log(bar()); //1

https://jsfiddle.net/mve3crm5/

I expect both foo() and bar() to return 1.

However, foo() returns undefined, bar() returns 1.

Assuming this is expected behaviour, Why?

I don't use JavaScript often so this confuses the heck out of me. A friend recommended I use "strict mode" but I tried it and the same behaviour happens.

I tested this on Chrome and node v7.4.0, also with the node --use_strict flag.

I had my expression on a new line because the particular expression I was returning wasn't complicated but quite long. I split the expression into multiple lines and was surprised to get an undefined value.

I debugged everything in the system and concluded there was nothing wrong except the return statement but refused to believe it. Then, I tried to put together a minimal example and saw that it is, indeed, the case.

I am forced to believe that this is how JavaScript works, despite still being skeptical. I am partially convinced I probably have a typo somewhere, somehow.

Justin AnyhowStep
  • 1,130
  • 3
  • 12
  • 19
  • 2
    It’s called “automatic semicolon insertion” and is one of JavaScript’s stupidest features. Linters can catch this for you, though. – Ry- Jan 27 '17 at 04:01
  • I'm not an expert either, but JavaScript automatically adds semi colons to the end of the line. So it probably becomes return; 1; Since this behavior is slightly unpredictable people try to code in a way that prevents JavaScript from guessing – DerrickHo328 Jan 27 '17 at 04:02
  • 1
    `JavaScript automatically adds semi colons to the end of the line` under some circumstances only – Jaromanda X Jan 27 '17 at 04:02
  • Ryan is correct, and now we're stuck with it because changing it would mean all those *we don't need semicolons anymore* proponents out there would suddenly have broken code. – CatDadCode Jan 27 '17 at 04:05
  • Agh, that's horrible. I'm looking at this now: http://inimino.org/~inimino/blog/javascript_semicolons and it has an example with the exact issue I encountered today =/ – Justin AnyhowStep Jan 27 '17 at 04:14
  • TIL, thanks, guys! – Justin AnyhowStep Jan 27 '17 at 04:15

0 Answers0