66

I was under the impression semicolons became obsolete with ES6. However, I came across this today:

Doesn't work:

let i = 0

[0, 1, 2, 3, 4, 5, 6].forEach(item => console.log(item))

Works:

let i = 0;

[0, 1, 2, 3, 4, 5, 6].forEach(item => console.log(item))

Why is the semicolon necessary here, and when should I use them?

seven11
  • 895
  • 1
  • 7
  • 14
  • 15
    Where did you get this idea that semicolons became obsolete??!? – Amit Jan 22 '16 at 15:41
  • 9
    semicolons haven't become obsolete, automatic semicolon insertion has always been part of js. Starting a line with a square bracket is a case where adding a semi colon saves you from an asi error https://youtu.be/Qlr-FGbhKaI?t=5m58s – Christine Jan 22 '16 at 15:41
  • 8
    The [rules for automatic insertion of semicolons](http://www.ecma-international.org/ecma-262/6.0/#sec-automatic-semicolon-insertion) is still basically the same in ES2015 as it always was – adeneo Jan 22 '16 at 15:41
  • 2
    From here: [https://github.com/rse/es6-features](https://github.com/rse/es6-features#frequently-asked-questions-faq) – seven11 Jan 22 '16 at 15:43
  • This isn't really any different in ES6 (with `let`) than in ES5 (with `var`). – Bergi Jan 22 '16 at 15:45
  • 1
    @user5626500 That github link talks about tooling capabilities and style choices; nothing about changes to the rules behind semicolons. – Dave Newton Jan 22 '16 at 15:59
  • an excellent explanation of the semicolon gotcha: http://inimino.org/~inimino/blog/javascript_semicolons – odigity Dec 15 '16 at 01:01
  • 1
    An article on React.js best practices https://blog.risingstack.com/react-js-best-practices-for-2016/ says, "That's right, we do not use semicolons anymore." – Marcus Jan 01 '17 at 03:44
  • I had the same question, and the way you asked it got four different topics addressed at once: 1. Didn't ECMA6 remove the semicolons. Answer: (1a) No, they where always only a choice and still are. (1b) The ECMA6 adopts a semicolonless *style* (2). So why did this happen (2a) technical explanation. (2b) use a linter to avoid. – pashute Jun 30 '20 at 21:15

1 Answers1

54

Without the semicolon [1,2,3,4,5,6] will be evaluated as property access. Which is perfectly fine JS, I personally don't think that adding semicolons is such a big deal so I keep using them.

Evers
  • 1,858
  • 1
  • 17
  • 18
  • 16
    Let's call it "property access", not "index of an array". In `0[6]`, there is no array. – Bergi Jan 22 '16 at 15:46
  • 11
    As an alternative to always using semicolons, linting tools can be used to catch these ambiguous scenarios for you, e.g. http://eslint.org/docs/rules/no-unexpected-multiline, this way you can keep the general rule of no semicolons, but add them in where necessary. – mikeapr4 Sep 01 '16 at 12:10