When semicolon isn't optional in JavaScript
TL;DR: In JavaScript, semicolons are optional at the end of statements, but there are specific cases where omitting them can lead to unexpected behavior or errors.
Without semicolon:
In the following example, I am trying to access an element in an array using idx variable and console log if the number is even or odd.
And since semicolon is optional in JavaScript, I have not used any semicolon at the end of the statement.
Everything seems fine, right?
But wait, we got errors in the console.
With semicolon:
Now let's add semicolons at the end of the statements.
And look that, Everything works fine now!
So WTF?
The deal breaker line here is const num = array[idx]. Because is it followed by (num && num % 2 === 0) ? console.log("Even") : console.log("Odd");
Why? Lets say our array contained functions that returns a number.
It logs function fn3() {} in the console.
But we want num to be the return value of the function. So we need to call the function like this: const num = array[idx]() that way num will be the return value of the function.
Since fn3 doesn't take any arguments, its deosnt matter if we pass any argument or not the function will still return the same value.
And we could also call the function in the next line and it will still work the same way.
Did you catch it?
In our first example we were accidentally performing a function call on array[idx] which is a number and not a function, which is obviously wrong.
But when we add a semicolon at the end of the statement: const num = array[idx] the statement ends and the next line is treated as a new statement and not a function call.