Javascript error when

I am reducing Javascript in production using jsMin.php https://github.com/rgrove/jsmin-php/

Here is the uninstalled JS code:

function arc(r, p, a) { return "A" + r + "," + r + " 0 " + +(a > Math.PI) + ",1 " + p; } 

and abbreviated code:

 function arc(r,p,a){return"A"+r+","+r+" 0 "++(a>Math.PI)+",1 "+p;} 

When mining, the code generates an "unexpected identifier" error. If I take the + sign in front of (a > Math.PI) , it will work fine.

I think my question consists of two parts: why is it a mistake when all this is on the same line, and I change the way it works by removing the "+" sign? This seems like normal, but I didn't write the code, so I'm not quite sure what it does.

+1
javascript minify
source share
2 answers

You should not receive the "unexpected identifier" error from the mini-code you submitted. If so, this is a bug in the JavaScript engine with which you use it. This is true for the code you posted originally:

 function arc(r,p,a){return"A"+r+","+r+" 0 "+ +(a>Math.PI)+",1 "+p;} // You used to have a space here -----------^ 

But with the updated code you posted:

 function arc(r,p,a){return"A"+r+","+r+" 0 "++(a>Math.PI)+",1 "+p;} // No space here anymore -------------------^ 

... this is a problem because ++ is an increment operator (either the prefix [ ++a ] or the postfix [ a++ ]). And for this you need an identifier (a thing to increase). ++ simply invalid in this position (the exact error you get may vary depending on the JavaScript mechanism).

You can protect the code from the minifier by doing this by slightly changing it:

 function arc(r, p, a) { return "A" + r + "," + r + " 0 " + (+(a > Math.PI)) + ",1 " + p; } 

Paranas prevent the combination of + and other + in ++ . They also make the intention a little clearer, IMHO.


I repeat the second part of your question, no, you cannot delete this + , this will change the function. In particular, a > Math.PI will be true or false , and + should make it a number ( 1 for true , 0 for false ) before it is concatenated with a string. If you delete it, you will see true or false in the line instead of 1 or 0 .

+7
source share

I think the problem does not really exist, but earlier, even if it looks here because the function token is invalid. Try to add ; :

 ;function arc(r,p,a){return"A"+r+","+r+" 0 "+ +(a>Math.PI)+",1 "+p;}; 

I am a little surprised that the minifier admitted ; to } . It's useless.

+1
source share

All Articles