Why so many semicolons in JavaScript?

前端 未结 10 1768
夕颜
夕颜 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 03:56

    This is probably going to remain a debatable question as to the origin of how this this manner of coding came to be, but it could have come from the ability to differentiate between 1 and many statements within an if conditional, which is common in most languages. And also, people could have confused syntax with JavaScript's object literal

    First, you have the single statement if:

    if (someNumber == 2)
      doSomething();
    else
      doSomethingElse();
    

    Then, you have the multi-statement if (no semi-colon needed):

    if (someNumber == 3) {
      doThisFirst();
      doThisSecond();
    } else
      doSomethingElse();
    

    This syntax could also be confused with JavaScript's object literal, which does need a semi-color:

    var SomeObjectLiteral = {
      property: 2,
      doSomething: function() {
      }
    };
    

    Basically, the semi-colon is important in Javascript to determine where a command, or definition, ends. And Braces are just as important to determine blocks of these commands. But, you can have as many semi-colons as you want. If in doubt, use a semi-colon, but be prepared if someone calls you out for not needing one :)

提交回复
热议问题