Are semicolons needed after an object literal assignment in JavaScript?

前端 未结 7 1609
北海茫月
北海茫月 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:12

    Use JSLint to keep your JavaScript clean and tidy

    JSLint says:

    Error:

    Implied global: alert 2

    Problem at line 3 character 2: Missing semicolon.

    }

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 17:16

    The semi-colon is not necessary. Some people choose to follow the convention of always terminating with a semi-colon instead of allowing JavaScript to do so automatically at linebreaks, but I'm sure you'll find groups advocating either direction.

    If you are looking at writing "correct" JavaScript, I would suggest testing things in Firefox with javascript.options.strict (accessed via about:config) set to true. It might not catch everything, but it should help you ensure your JavaScript code is more compliant.

    0 讨论(0)
  • 2020-12-03 17:17

    In this case there is no need for a semicolon at the end of the statement. The conclusion is the same but the reasoning is way off.

    JavaScript does not have semicolons as "optional". Rather, it has strict rules around automatic semicolon insertion. Semicolons are not optional with statements like break, continue, or throw. Refer to the ECMA Language Specification for more details; specifically 11.9.1, rules of automatic semicolon insertion.

    0 讨论(0)
  • 2020-12-03 17:21

    The YUI Compressor and dojo shrinksafe should work perfectly fine without semicolons since they're based on a full JavaScript parser. But Packer and JSMin won't.

    The other reason to always use semi-colons at the end of statements is that occasionally you can accidentally combine two statements to create something very different. For example, if you follow the statement with the common technique to create a scope using a closure:

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

    The parser might interpret the brackets as a function call, here causing a type error, but in other circumstances it could cause a subtle bug that's tricky to trace. Another interesting mishap is if the next statement starts with a regular expression, the parser might think the first forward slash is a division symbol.

    0 讨论(0)
  • 2020-12-03 17:26

    Not technically, JavaScript has semicolons as optional in many situations.

    But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.

    Automatic semicolon insertion is performed by the interpreter, so you can leave them out if you so choose. In the comments, someone claimed that

    Semicolons are not optional with statements like break/continue/throw

    but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference.

    Here is the rest of the standard on semicolon insertion:

    For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.

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