Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semi Colon Issue in JS [duplicate]

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.

like image 520
Sachin Avatar asked Dec 16 '15 04:12

Sachin


People also ask

Does JavaScript care about semicolons?

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).

Why does JavaScript work without semicolon?

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.

When we should use semicolon in JavaScript?

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.

What is the semi colon at the end of a piece of JavaScript code?

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.


1 Answers

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.

like image 198
Ramanlfc Avatar answered Oct 14 '22 06:10

Ramanlfc