Automatic semicolon insertion

Although JavaScript has the CODE style of C, it does not mandate the use of semicolons in code and can actually omit them.

JavaScript is not a language without semicolons; on the contrary, it needs semicolons to parse source code. So the JavaScript parser automatically inserts semicolons into the source code when it encounters a parsing error due to the lack of a semicolon.

Var foo = function() {}Copy the code

Automatically inserts semicolons and the parser reparses.

var foo = function() { }; // No error, parsing continues test()Copy the code

Automatic semicolon insertion is considered one of the biggest design flaws of the JavaScript language because it can change the behavior of code.

The working principle of

The following code does not have semicolons, so it is up to the parser to figure out where to insert semicolons.

(function(window, undefined) { function test(options) { log('testing! ') (options.list || []).forEach(function(i) { }) options.value.test( 'long string to pass here', 'and another long string to pass' ) return { foo: function() {} } } window.test = test })(window) (function(window) { window.someLibrary = {} })(window)Copy the code

Here’s the parser.”guess“.

(function(window, undefined) {function test(options) { ')(options.list || []).forEach(function(i) { }); // <- insert semicolon options.value.test('long string to pass here', 'and another long string to pass'); // <- insert semicolon return; Foo: function() {}}; foo: function() {}}; // <- insert semicolon} window.test = test; })(window)(function(window) {window.somelibrary = {}; // <- insert semicolon})(window); //<- insert semicolonCopy the code

The parser significantly changes the behavior of the code above, and in other cases makes errors as well.

Front bracket

In the case of leading parentheses, the parser does not automatically insert semicolons.

log('testing! ') (options.list || []).forEach(function(i) {})Copy the code

The above code is converted to one line by the parser.

log('testing! ')(options.list || []).forEach(function(i) {})Copy the code

The result of the log function is most likely not a function; In this case, TypeError occurs, which may say undefined is not a function.

conclusion

It is recommended that you never omit the semicolon. It is also recommended that the curly braces and the corresponding expression be placed on the same line, and that the curly braces should not be omitted for an if or else expression that has only one line of code. These good programming practices not only address code consistency, but also prevent parser error handling that changes code behavior.