简体   繁体   中英

JavaScript return statement unexpected

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?

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM