Are semicolons needed after an object literal assignment in JavaScript?

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

    This is not valid (see clarification below) JavaScript code, since the assignment is just a regular statement, no different from

    var foo = "bar";
    

    The semicolon can be left out since JavaScript interpreters attempt to add a semicolon to fix syntax errors, but this is an extra and unnecessary step. I don't know of any strict mode, but I do know that automated parsers or compressors / obfuscators need that semicolon.

    If you want to be writing correct JavaScript code, write the semicolon :-)

    According to the ECMAscript spec, http://www.ecma-international.org/publications/standards/Ecma-262.htm, the semicolons are automatically inserted if missing. This makes them not required for the script author, but it implies they are required for the interpreter. This means the answer to the original question is 'No', they are not required when writing a script, but, as is pointed out by others, it is recommended for various reasons.

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