Why so many semicolons in JavaScript?

前端 未结 10 1783
夕颜
夕颜 2021-02-13 03:22

I tend to be a prolific user of semicolons in my JavaScript:

var x = 1;
var y = 2;
if (x==y){do something};

I recently noticed that I was looki

10条回答
  •  青春惊慌失措
    2021-02-13 04:02

    Many computer languages use semicolons to denote the end of a statement. C, C++, and Java are popular examples of this.

    As for why people use them despite them being optional, they improve the readability of your code. In most cases it's simply done out of habit, but occasionally you need semicolons in your code to remove possible ambiguity. It's always better safe (and consistent) than sorry.

    Here is an example taken from Do you recommend using semicolons after every statement in JavaScript?

    // define a function
    var fn = function () {
        //...
    } // semicolon missing at this line
    
    // then execute some code inside a closure
    (function () {
        //...
    })();
    

    This will be interpreted as:

    var fn = function () {
        //...
    }(function () {
        //...
    })();
    

    Additionally, semicolons allow Javascript to be packed/minified properly. Otherwise all the statements will be mushed together into one big mess.

提交回复
热议问题