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:
.
or ,
:javascriptlet array = [ 'erik', 'jeff', 'elon' ] let l = array. length
++
or --
:javascriptlet age = 34 ++ age // 35 // It's weird to find code written like this
{
:javascriptwhile(true) console.log('Hello, world') if(true) console.log('Bye, world')
javascriptconst 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:
javascriptconst 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.