2

Why is the semi-colon required after the string toInsert for the forEach to work?

const toInsert = "";

['Heading Font','Body Font'].forEach(f=>{
    console.log(f)
})

If I remove the semi-colon, it gives me an error Uncaught TypeError: Cannot read property 'forEach' of undefined

I thought semicolons were not required in JS?

  • 3
    It's because of the rules of automatic semicolon insertion. Either learn the subtle and complicated rules, or always use semicolons. – Pointy Feb 25 '21 at 03:15
  • 1
    @Pointy so what is the problem here ? – 27px Feb 25 '21 at 03:21
  • 3
    Because spaces are not important, so your code is basically: `const toInsert = ""['Heading Font','Body Font']...` which is interpreted as trying to access a character from the empty string `""` (like, for example, `"string"[2] === "r"`) – ibrahim mahrir Feb 25 '21 at 03:22
  • @ibrahimmahrir Not exactly the character but the property of the `""` object. For example `""['length']` will return `0` and `""['toUpperCase']` will return a function. However the point holds that `""[xxx]` is valid syntax in javascript – slebetman Feb 25 '21 at 04:08
  • 1
    To the OP: You **MUST** either always use semicolons (my preference) or follow standardjs (https://standardjs.com/). There is no in-between. If you don't use semicolons but don't follow standardjs style guide you will have errors like this. BTW, standardjs says you cannot ever end lines with semicolons so your fix would be wrong. All square brackets at the start of the line needs to be prepended with a semicolon so the correct fix would be `;['Heading Font', ...` instead of `... "";` – slebetman Feb 25 '21 at 04:12

0 Answers0