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

前端 未结 3 1441
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 12:35

Consider the following JavaScript:

相关标签:
3条回答
  • 2020-11-22 12:52

    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.

    0 讨论(0)
  • 2020-11-22 13:07

    The command line of the javascript can not be broken by line breaks. But arguments of functions can be broken, not highly recommended (done in your example).

    0 讨论(0)
  • 2020-11-22 13:09

    If there is nothing after the return statement on that line then ; will be inserted there which will result in returning without any values => return value is undefined.

    See: http://lucumr.pocoo.org/2011/2/6/automatic-semicolon-insertion/

    0 讨论(0)
提交回复
热议问题