javascriptecmascript-2018

Semicolon before square bracket


Can anyone tell me why yarn format is adding a semi colon before my square brackets. Yarn build fails without it..

    ;[
      this.querySelector('[class$="-cover"] img'),
      this.querySelector('.FullscreenCarousel-cover-count')
     ].forEach(item => {
         // actions
    })
    })

Solution

  • Consider the following (basic) code:

    doSomething()
    [1].forEach(i => doAnotherThing(i))
    

    Reading it this way, it looks straightforward--call some function, and then iterate over an array and call another function. Two separate steps.

    However, JS doesn't look at whitespace. What if you saw the code like this:

    doSomething()[1].forEach(i => doAnotherThing(i))
    

    What does that now mean? Now it looks like you need to call doSomething() which returns an array, take item 1 of that array, and hopefully that is an array because we are iterating over it.

    As opposed to:

    doSomething();[1].forEach(i => doAnotherThing(i))
    

    Which also condenses the whitespace but now is clear that you mean these to be two completely separate steps. The primary reason for prepending with a semicolon like that is to clarify your intentions.