When is it dangerous to line break after a close parenthesis in Javascript?

后端 未结 4 1820
一生所求
一生所求 2021-01-18 03:37
  • What are the dangers of breaking a line of long code up at a close parenthesis?

  • When could a semicolon be automatically inserted by Javascript (pres

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 04:30

    When you're trying to return an object,

    return {
     'foo': 'bar'
    }
    

    will return the object, whereas

    return
    {
      'foo': 'bar'
    }
    

    will return undefined. Javascript will automatically insert a semicolon after return in the second example, and the object will never be reached.

    For functions, because function() isn't valid on its own, it shouldn't make a difference if the brace is on the same line or the next.

    See also section 7.9.1 Rules of Automatic Semicolon Insertion of the ECMAScript specification. Aside from return, there are four other situations where a semicolon will be inserted due to a newline: break, continue, throw and ++ or --.

    When a continue, break, return, or throw token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after the continue, break, return, or throw token.

提交回复
热议问题