7

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.

Bhargav Rao
  • 41,091
  • 27
  • 112
  • 129
sachinjain024
  • 19,669
  • 27
  • 88
  • 154
  • The semi-colon behind the closing brace of function1 specifies that its an anonymous function. Its the syntax of jQuery using which anonymous functions are being written. – Vinit Sharma Dec 16 '15 at 04:44
  • Simply You're trying to write two instruction in a single line.If you put `window.project = 'test';` in new line, we don't need `;` after curly brackets but I prefers the semicolon and single instruction per single line :) – Bibek Sharma Dec 16 '15 at 04:44

3 Answers3

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

Ramanlfc
  • 7,900
  • 1
  • 14
  • 24
1

In Javascript the semicolon can be omitted if the statement is followed by a line break.

Here you have 2 statements in the same line, so the first semicolon is obligatory.

But you could write something like:

window.function1 = function() {
  console.log('function 1');
}; window.project = 'test'

(without the last semicolon)

More details here: https://www.codecademy.com/forum_questions/507f6dd09266b70200000d7e

Ekow
  • 21
  • 2
0

function1 is a variable, which does not appear to be concluded before window.project ; js interpreting both variables as function1. Could add a comma , operator following function1 declaration to avoid syntax error between the two variables function1, project

window.function1 = function() {
  console.log('function 1');
}, window.project = 'test';
guest271314
  • 1
  • 10
  • 82
  • 156