Let's understand the scenario using following code.
1st Scenario: var x [1,2,4].forEach(console.log)
2nd Scenario: var x = 10 (or console.log('anything') ) [1,2,4].forEach(console.log)
so in javascript interpreter puts a semicolon at the end of each line but in "1st scenario : it gives expected result but not in 2nd scenario"
Can anybody here please help me in understanding this?
so in javascript interpreter puts a semicolon at the end of each line
Your assumption is wrong. It's easier to think of ASI as statement separation (which has nothing to do with lines!), because that's the intention and what it does. However, a bracket is not a new statement, so it will not be separated and instead interpreted as though it was a part of the previous statement.
So, the 2nd scenario is interpreted as though you would have written
var x = 10[1,2,4].forEach(console.log);
I recommend using a linter (like ESLint), which can mark problematic situations like that as warnings or errors in your code, so you can review and correct them before even running the code. Personally, I also recommend using semicolons, as that's how most languages work and you will find it a lot easier to learn them if you just use semicolons all the time.
they auto inject the semicolon.
try this ;)
function x() {
return
12;
}
function y() {
return (
12
);
}
console.log(x());
console.log(y());
and actually it gives the expected result since newline and no opened scope so it injects ;
JS is bad language design that's nothing new.
destroyallsoftware.com/talks/wat
it has different advantages.
Pretty much this is why you should NOT blindly trust that omitting them is ok. If it should be there, SAY IT!
That they're optional in the first place was a pretty damned stupid idea... but that can be said about a LOT of the decisions made early-on in during JS creation that we struggle with to this day.
Whilst if you're looking for the "why" that's like asking why IE doesn't work like other browsers. It's IE, that's reason enough... in this case it's JavaScript, that's reason enough.
Peter Scheler
JS enthusiast
There are some rules for ASI (automated semicolon insertion). If you start a line with a bracket (or a regex) ASI will not tread them as a new statement.
To do so, you have to place a semicolon in front of the statement (same line or the line before).
If you would like to omit all semicolons (like me), you can also use
void:void [1,2,4].forEach(console.log)