Paul Mackey
Paul Mackey

Reputation: 95

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
    })
    })

Upvotes: 1

Views: 1814

Answers (2)

AbdulmateenChitrali
AbdulmateenChitrali

Reputation: 389

console.log('First line')
['a', 'b', 'c'].forEach((element) => console.log(element))
console.log('Third line')
  • 1: First line, then print a, b, c in a new line, and finally print Third line as next line
  • 2: First line, then print a, b, c in a first line, and print Third line as next line
  • 3: Missing semi-colon error
  • 4: Cannot read properties of undefined
Answer

##### Answer: 4

When JavaScript encounters a line break without a semicolon, the JavaScript parser will automatically add a semicolon based on a set of rules called Automatic Semicolon Insertion which determines whether line break as end of statement or not to insert semicolon. But it does not assume a semicolon before square brackets [...]. So the first two lines considered as a single statement as below.

console.log('First line')['a', 'b', 'c'].forEach((element) => console.log(element))

Hence, there will be cannot read properties of undefined error while applying the array square bracket on log function.

Upvotes: 0

mherzig
mherzig

Reputation: 1587

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.

Upvotes: 11

Related Questions