JavaScript compilation error

I noticed a strange thing when writing JS code. This compilation error seems to occur in multiple browsers (tested: Chrome, IE, Safari). I am not in a hurry to solve, but I could not understand why this code would not compile:

function fooBar1()//Compiles { return { x: 0, y: 1 }; } function fooBar2()//Compiles { return {x: 0, y: 1}; } function fooBar3()//Compiles { return { x: 0 }; } function fooBar4()//Does not compile { return { x: 0, y: 1//Uncaught SyntaxError: Unexpected token : }; } 
+4
source share
2 answers

This is due to the "Automatic Javascript semicolon" function.

I put the word "function" in quotation marks because it really is nothing but - it is frankly a bit of a disaster; one of the worst design decisions that I know in the language.

In principle, the JS language is designed to ensure that all statements end with a semicolon, but the original design of the language made a discount for coders who forgot it, and therefore, if he sees a line break without a half-colony, he tries to guess if he should be there.

Unfortunately, there are times when this leads to ambiguity and errors, and return are probably the worst for this.

In the final example, { for the returned object is in the line after the return . This is a classic case for this kind of error. JS automatically inserts the half-hour after return , and the object you planned to return is ignored.

The simple answer is: just do not do it like this. Always put the object on the same line as the return . Remember that return requires that the data returned be on the same line (or at least start on the same line) as the return itself.

Closest you can go to your broken example and still have it working, shown in your first example.

 return { x: 0, y: 1 }; 

As a final thought, you may need to run JS code using the jsLint tool, which will pick up errors like this (and other potential problems).

+1
source

Mistakes like these can really drive you crazy, right?

I assume the javascript parser adds a semicolon right after returning to fooBar4. (he "thinks" that you wanted it)

at least when I change any of your working functions by adding a semicolon after returning, the same syntax error will appear

0
source

All Articles