Why so many semicolons in JavaScript?

前端 未结 10 1767
夕颜
夕颜 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:38

    you can write multiple statement within the function with help of semicolon; semicolon used to separate the statement. easy to understand.

    0 讨论(0)
  • 2021-02-13 03:40

    The C language uses semicolons at the end of statements, and also uses braces.

    0 讨论(0)
  • 2021-02-13 03:47

    Apart from code readability, the use of semi-colons comes into picture when you actually try to minify your code. After minification, if there are no semicolons in your code, javascript engine might fail to know which statement ends where as there will be no longer be any new lines in the code.

    0 讨论(0)
  • 2021-02-13 03:52

    JavaScript requires semicolons. But it does have Automatic Semi-colon Insertion.

    The majority of JavaScript programmers are smarter than ASI and prefer to be explicit with their semi colons.

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

    0 讨论(0)
  • 2021-02-13 03:57

    Semicolons mark the end of statements in JS, but I do not put semicolons after a close-brace, only after a statement within a brace and ALWAYS on a return statement.

    In your example I dont find it necessary.

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