Many JavaScript developers often suggest using semicolon for better readability. However, readability is not the only purpose to use semicolon in JavaScript. Though JavaScript supports Automatic Semicolon Insertion
, it is not supported in every scenario and causes unexpected error sometimes.
Example 1
console.log(1)
console.log(2)
Example 2
console.log('Causes Error')
[1, 2].forEach(console.log(1))
Example 1 will execute fine and logs the number 1
and 2
. Whereas, Example 2 will throw an error after logging the Causes Error
message. Because JavaScript compiler consider both line code into a single ExpressionStatement as per the language grammar and leads to the error
console.log('Causes Error')[(1, 2)].forEach(console.log(1));
For more information and reference head to the below blog post and specification
https://codeburst.io/ecmascript-automatic-semicolon-insertion-50f09091e377