Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

Why doesn't a Javascript return statement work when the return value is on a new line?

Consider the following JavaScript:

function correct()
{
    return 15;
}

function wrong()
{
    return
          15;
}

console.log("correct() called : "+correct());
console.log("wrong() called : "+wrong());
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Technically, semi colons in javascript are optional. But in reality it just inserts them for you at certain newline characters if it thinks they are missing. But the descisions it makes for you are not always what you actually want.

And a return statement followed by a new line tells the JS intepreter that a semi colon should be inserted after that return. Therefore your actual code is this:

function wrong()
{
    return;
          15;
}

Which is obviously wrong. So why does this work?

function wrong()
{
     return(
           15);
}

Well here we start an expression with an open(. JS knows we are in the middle of an expression when it finds the new line and is smart enough to not insert any semi colons in this case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...