14

Why is it that in node.js, some things do not need / generally do not use semicolons? For example this code runs just fine with no semicolons =>

var server = app.listen(3000, function() {
    var host = server.address().address
    var port = server.address().port
    console.log("App is listening on port 3000...")
})

3 Answers3

20

Because NodeJS runs on the Chrome's V8 JavaScript engine. It's basically JavaScript that runs on the server and in JavaScript there is this thing called Automatic Semicolon Insertion.

That V8 engine that parses the JavaScript will follow certain rules (according to ECMAScript specs) and insert the semicolon automatically when it is not present.

There is plenty of articles on Automatic Semicolon Insertion if you wanna google it more, e.g. what are the rules, when it fails, etc.

Bergur
  • 3,962
  • 12
  • 20
6

The javascript parser tries to do its best to translate what you're trying to write. But sometimes it can be very ambiguous, consider this example

function(x) {
    return 
       x
}

Should it be interpreted as return nothing? or return x. To avoid these issues add a ; at the end of each line

caverac
  • 1,505
  • 2
  • 12
  • 17
0

That is not specific to Node.js or even V8. It is a feature of Ecmascript(ES).Even the arrow functions that you encounter are Ecmascript feature. At certain point (ES6 I think), ES specification made semicolons optional.Some linting libraries will remove semicolons inserted.

SanSolo
  • 2,267
  • 2
  • 24
  • 32