Half Column Problem in JS

I happened to meet the following strange case:

One of the network calls answered like this:

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

But when the following script is evaluated, it returns an error

Unexpected id

This problem is fixed when a semi-colon added after defining function1. So the correct fix is:

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

I am curious to know the reason for this.

+7
javascript semicolon minify
source share
4 answers
 window.function1 = function() { console.log('function 1'); } window.project = 'test'; 

The js engine reads this whole thing as one statement, since it cannot find a semicolon for anonymous function assignment, it continues to analyze only for the search window.project = 'test and therefore gives you an error message.

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

here, because after an anonymous function you have a semicolon, the js engine can understand that these are two different statements.

+2
source share

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

Here you have 2 statements on the same line, so the first semicolon is required.

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

+1
source share

function1 is a variable that is apparently not enclosed before window.project ; js interpretation of both variables as function1 . May add a comma operator after declaring function1 to avoid a syntax error between two variables function1 , project

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

Hope you get the answer below:

The reason is that you are using: Initializer of access function (ES5 +)

More details:

var functionName = function () {} vs function functionName () {}

-one
source share

All Articles