Dave Hilditch
Dave Hilditch

Reputation: 5439

Why does javascript produce different errors for strings and literals with ++?

I just discovered a bug in a 3rd party wordpress plugin that looks to have been caused by a javascript code minifier.

The original code, I believe, was supposed to be this:

this.id = "ui-id-" + ++n;

Instead it had been minified to:

this.id="ui-id-"+++n;

This results in the following error in Chrome:

Uncaught ReferenceError: Invalid left-hand side expression in postfix operation 

And a similar error in Firefox. Annoyingly, in Chrome my own plugins Javascript functions were still created successfully but in Firefox this error caused my functions not to be created and my plugin to fail.

var n = 1;
var foo = 10;
var bar = "ID-";
console.log(foo+++n); // results in 11
console.log(foo); // also results in 11
console.log(bar+++n); // results in NaN soft error/warning
console.log ("ID-"+ ++n); // results in ID-2
console.log ("ID-"+++n); // hard error

I'm not really sure what question to ask here -

  1. Why does +++ always get interpreted as ++ +?
  2. Which minifiers cause this bug?
  3. Why does firefox treat this error more seriously than Chrome and cause my own javascript functions in Wordpress to fail to be created?
  4. Why does bar++ get a soft error (NaN) but "ID-"++ gets a hard error?

Upvotes: 5

Views: 134

Answers (1)

user1046334
user1046334

Reputation:

I see the question 4. the only interesting one, so I answer only that (1. is trivial: "it is that by definition of language", 2. I don't know, 3. I do not understand):

The answer lies in the error you cite:

Uncaught Reference Error: Invalid left-hand side expression in postfix operation

++ is modifying operation, it needs "left hand side expression". bar is variable, so it is LHS, "ID-" is a literal, so it is not a LHS.

Upvotes: 1

Related Questions