3
function returnSomething(){
    return 
    5;
}

This return undefined.

function returnSomething(){
    return 5;
}

This returns 5.

When I add new line after return, undefined is returned. I am using chrome. Is it the way V8 works?

Akhilesh
  • 47
  • 11
  • In JS, you don't have to add semicolons to the end of the statement. There are some rules, when a newline is also a statement ending. Just google it. – ssc-hrep3 Jul 05 '18 at 05:53
  • Go through https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi – vibhor1997a Jul 05 '18 at 05:54

2 Answers2

4

This is the way JS works. Returns MUST begin the return block in the same line:

return {};

will return undefined, you should return: return {};

or

return { };

or

const isValid = false;
return isValid
    ? 5
    : 3;

By the way this is not v8, this is how JS has always worked

A. Llorente
  • 1,142
  • 6
  • 16
  • 3
    `Returns MUST return in the same line` Not necessarily - if the syntax is invalid otherwise (for example, beginning of an object literal, or conditional operator) but valid if interpreted as one expression over multiple lines being returned, then that whole expression will be returned. – CertainPerformance Jul 05 '18 at 05:54
  • Hi @CertainPerformance Can you give an example of what you mean? It is not entirely clear for me. I understand that the return can use multiple lines, what I meant is that it should start in the same line (second example, return is splitted in two lines, but the object starts in the same line as the return). – A. Llorente Jul 05 '18 at 05:57
  • `for example, beginning of an object literal, or conditional operator` – CertainPerformance Jul 05 '18 at 05:58
  • I think we are on the same page :) I will update the piece of my answer that you pointed out to explain it better. Thanks! – A. Llorente Jul 05 '18 at 06:00
0

The number 5 is in new line. return statement ends in the single line even if you don't give the semi colon.
So your code is similar to :

function returnSomething(){
    return; // returns undefined.
    5;
}
Karthik
  • 112
  • 8