Are semicolons needed after an object literal assignment in JavaScript?

前端 未结 7 1721
北海茫月
北海茫月 2020-12-03 16:38

The following code illustrates an object literal being assigned, but with no semicolon afterwards:

var literal = {
    say: function(msg) { alert(msg); }
}
l         


        
7条回答
  •  感情败类
    2020-12-03 17:13

    JavaScript interpreters do something called "semicolon insertion", so if a line without a semicolon is valid, a semicolon will quietly be added to the end of the statement and no error will occur.

    var foo = 'bar'
    // Valid, foo now contains 'bar'
    var bas =
        { prop: 'yay!' }
    // Valid, bas now contains object with property 'prop' containing 'yay!'
    var zeb =
    switch (zeb) {
      ...
    // Invalid, because the lines following 'var zeb =' aren't an assignable value
    

    Not too complicated and at least an error gets thrown when something is clearly not right. But there are cases where an error is not thrown, but the statements are not executed as intended due to semicolon insertion. Consider a function that is supposed to return an object:

    return {
        prop: 'yay!'
    }
    // The object literal gets returned as expected and all is well
    return
    {
        prop: 'nay!'
    }
    // Oops! return by itself is a perfectly valid statement, so a semicolon
    // is inserted and undefined is unexpectedly returned, rather than the object
    // literal. Note that no error occurred.
    

    Bugs like this can be maddeningly difficult to hunt down and while you can't ensure this never happens (since there's no way I know of to turn off semicolon insertion), these sorts of bugs are easier to identify when you make your intentions clear by consistently using semicolons. That and explicitly adding semicolons is generally considered good style.

    I was first made aware of this insidious little possibility when reading Douglas Crockford's superb and succinct book "JavaScript: The Good Parts". I highly recommend it.

提交回复
热议问题