Rethinking the JavaScript semicolon

Semicolons were part of C++ when I studied at the university. I adopted the same habit of writing a semicolon at the end of each line of code in JavaScript, but there aren't mandatory, so I decided to type less and stopped using them a few weeks ago.

In general, a line-break \n ends a JavaScript statement unless:

  1. The line ends with . or ,:
javascript
let array = [
    'erik',
    'jeff',
    'elon'
]

let l = array.
        length
  1. The line is ++ or --:
javascript
let age = 34
++
age
// 35
// It's weird to find code written like this
  1. Loop or conditions without {:
javascript
while(true)
    console.log('Hello, world')

if(true)
    console.log('Bye, world')
  1. The next line starts with a special symbol:
javascript
const hello = () => ['erik', 'jeff', 'elon']

hello()
[1, 2].forEach(e => console.log(e))
// Uncaught TypeError: hello(...)[(1 , 2)].forEach is not a function
// Here, a semicolon is required

You can solve this case by writing a semicolon (or a comma) at the end of the function, or a the beginning of the new line:

javascript
const hello = () => console.log('test')

hello(),
[1, 2].forEach(e => console.log(e))

Sites like GitHub are free from semicolons. From now on, I'll avoid them as well.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.