2
process.on('exit', function () {
    console.log("Exiting normally")
})

process.on('uncaughtException', function (err) {
    console.log("Caught - " + err)
})

[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})

This breaks with:

Caught - TypeError: Cannot read property 'forEach' of undefined

Exiting normally

Whereas when I add a semi-colon, it works:

process.on('exit', function () {
    console.log("Exiting normally")
})

process.on('uncaughtException', function (err) {
    console.log("Caught - " + err)
}); // Added semi colon here

[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})

Does this mean that I should be using semi-colons after every statement just to be safe?

Veneet Reddy
  • 2,707
  • 1
  • 24
  • 40
  • 1
    `process.on` doesn't end with line terminator `}`, hence automatic semicolon insertion doesn't happen. – gurvinder372 Nov 17 '17 at 06:15
  • 1
    Because JavaScript is silly and assumes things unless you explicitly close statements with semicolons. It now assumes the angle brackets are indexing for the previous statement. And yes, using semicolons is a good thing to stop this. – Sami Kuhmonen Nov 17 '17 at 06:15
  • Generally, you should terminate your statements with a semicolon. http://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript – Walter Stabosz Nov 17 '17 at 06:16
  • People should only be allowed to omit semicolons if they understand automatic semicolon insertion. *"Does this mean that I should be using semi-colons after every statement just to be safe?"* The grammar rules actually dictate that [expression statements are terminated with a semicolon](https://www.ecma-international.org/ecma-262/8.0/#sec-expression-statement). – Felix Kling Nov 17 '17 at 06:16
  • This is why most linters will give you a warning about using methods on array literals, ie `[...].method()` – Phil Nov 17 '17 at 06:16

2 Answers2

1

Suppose you have a function returnArray() that returns, you guessed it, an array.

lets say you make this call:

#do stuff
returnArray();
[n].blah
#do other stuff
#this returns an array. say [1,2,3,4,5];
#and in the next line it does [n].blah

now lets say you make the same call without the semicolon

#do stuff
returnArray()
[n].blah
#do stuff
#this effectively does [1,2,3,4,5][n]
#which is the nth index element of the returned array.

this is similar to getting the n'th index of the returned array, which is typically not what you were trying to do.

Vj-
  • 722
  • 6
  • 18
0

when you dont use semicolon javascript consider it in following way

process.on('',function (err) {..})[1,2,3,4,5].forEach(function(element) {
    console.log("Loop " + element)
})

obliviously process.on() don't have any property like [1,2,3,4,5] which is why it was undefined

Hemant Rajpoot
  • 683
  • 1
  • 11
  • 29