Grim...
Grim...

Reputation: 16953

Javascript error when minified

I'm minifying Javascript in production with jsMin.php https://github.com/rgrove/jsmin-php/

Here is the unminified JS code:

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

and the minified code:

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

When minified, the code throws an 'unexpected identifier' error. If I take the + sign before (a > Math.PI) away, it works okay.

I guess my question has two parts - why is this an error when it's all on one line, and am I changing the way it works by removing the second + sign? It seems to work okay without it, but I didn't write the code so I'm not entirely sure what it's doing.

Upvotes: 1

Views: 9347

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

You shouldn't be getting an "unexpected identifier" error from the minified code you've presented. If you are, it's a bug in the JavaScript engine you're using it with. That was true of the code you posted originally, which was:

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've posted:

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

...it's a problem, because the ++ is an increment operator (either the prefix [++a] or postfix [a++]). And that would need an identifier (the thing to increment). The ++ just isn't valid in that position (the exact error you get is likely to vary by JavaScript engine).

You can defend the code against the minifier doing this by changing it slightly:

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

The parens prevent the + and the other + from getting combined into ++. They also make the intent a bit clearer, IMHO.


Re the second part of your question, no, you can't remove that +, it will change how the function works. In particular, a > Math.PI will be true or false, and the + is there to make it a number (1 for true, 0 for false) before it's concatenated to the string. If you remove it, you'll see true or false in the string instead of 1 or 0.

Upvotes: 7

Denys Séguret
Denys Séguret

Reputation: 382150

I guess the problem isn't really there, but just before, even if it looks like it's here because the invalid token is function. Try to add ; :

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

I'm a little surprised that the minifier did let the ; before the }, though. It's useless.

Upvotes: 1

Related Questions