Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ESLint error on semicolon after class declaration ECMAScript 6

I have the following code:

class Car() {

    constructor() {
        // ...
    }

    withSemi() {
        // ...
    };  // ESLint does not complain here

    withoutSemi() {
       // ...
    }  // ESLint does not complain here

};  // ESLint will complain about this semicolon (no-extra-semi)

Can someone explain how the automatic semicolon insertion will work in ES6 in regards to classes and why ESLint has this behaviour?

like image 687
adrianp Avatar asked Jun 15 '15 07:06

adrianp


1 Answers

According to the ECMAScript 2015 class specification, a semicolon is a valid ClassElement, so it can exist within a ClassBody.

However, its semantics treat it as having no behavior whatsoever (for example, see NonConstructorMethodDefinitions). Effectively you can have as many or as few semicolons you want in a ClassBody and it won't change a thing.

Automatic semicolon insertion actually doesn't come into play here, or as often as people think in general. Roughly speaking, ASI only happens when the parser sees something that wouldn't be allowed to be part of the previous block or line. (The actual rules for ASI aren't terribly long if you're interested; scroll down for examples and practical advice.) However in this context, you're allowed to put a bunch of class method definitions together sequentially. Thus there's nothing "unexpected" about the next method in the list, so no semicolon gets inserted between them.

I don't know the history of the decision, but I assume semicolons are valid ClassElements because they were already valid as empty statements, and it would probably be confusing for folks if you couldn't put semicolons in a class body.

like image 112
tdhsmith Avatar answered Sep 20 '22 01:09

tdhsmith