Why does the value returned should be on the same line as the return statement in JavaScript?

前端 未结 4 1644
南方客
南方客 2020-12-12 03:16

The following doesn\'t work as I would expect it to:

function test()
{
  // Returns undefined, even though I thought it would return 1
  return
  1;
}
         


        
4条回答
  •  醉梦人生
    2020-12-12 03:52

    Javascript automatically inserts a semicolon after the "return" statement if the return expression is not on the same line.

    JavaScript has a mechanism that tries to correct faulty programs by automatically inserting semicolons. Do not depend on this. It can mask more serious errors. It sometimes inserts semicolons in places where they are not welcome. Consider the consequences of semicolon insertion on the return statement. If a return statement returns a value, that value expression must begin on the same line as the return:

    return
    {
       status: true
    };
    

    This appears to return an object containing a status member. Unfortunately, semicolon insertion turns it into a statement that returns undefined. There is no warning that semicolon insertion caused the misinterpretation of the program. The problem can be avoided if the { is placed at the end of the previous line and not at the beginning of the next line:

    return {
       status: true
    };
    

    Quoted from this post, citing JavaScript: The Good Parts by Douglas Crockford. Copyright 2008 Yahoo! Inc., 978-0-596-51774-8.

提交回复
热议问题