I happened to come across the following weird case:
One of the network calls returned a response like this:
window.function1 = function() {
console.log('function 1');
} window.project = 'test';
But when the following script is getting evaluated, it is returning an error
Unexpected Identifier
This issue gets fixed when a semi-colon
is added after the function1 definition So the correct fix is:
window.function1 = function() {
console.log('function 1');
}; window.project = 'test';
I am curious to know the reason behind this.
JavaScript does not require semicolons (other than the one exception you saw earlier). This is because JavaScript is clever and it can add the semicolons where needed automatically. This happens behind the scenes and you will not notice it. This process is called Automatic Semicolon Insertion (ASI).
semi colons are required to separate statements. Since there's only a single statement in your onclick, there's an implied/invisible ; in there between the ) and the " . same thing. if the script block ends, there's an implied ; just before the end of the block.
The rules of JavaScript Automatic Semicolon Insertionwhen the next line starts with code that breaks the current one (code can spawn on multiple lines) when the next line starts with a } , closing the current block. when the end of the source code file is reached. when there is a return statement on its own line.
Answer 52b8cb427c82ca297c000836. In most cases, yes. JavaScript is an interpreted language, meaning it is parsed each time through and interpreted line by line, or statement by statement. The semi-colon signals JS of an 'end of statement' whereupon it quits parsing and executes it.
window.function1 = function() {
console.log('function 1');
} window.project = 'test';
js engine reads this entire thing as one statement ,since it can't find any semicolon for the anonymous function assignment, it continues parsing only to find window.project = 'test
and so it gives you an error.
window.function1 = function() {
console.log('function 1');
}; window.project = 'test';
here because you have a semicolon after the anonymous function, js engine can figure out that that these are 2 different statements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With