JSLint Error help

C++, C#, Java, PHP, ect...
Post Reply
Mardonis
Posts: 139
Joined: Wed Jun 29, 2011 7:54 pm

JSLint Error help

Post by Mardonis »

Some javascript code can say for example x++; or ++x; But JSLint wants it as x += 1; So my question is how to do yo it for the ++x;? I have tried 1 += x and it didnt like that. The same thing goes for x--; and --x; It allows x -= 1; but errors on 1 -= x; If you can't do the 1 -= x; then how do you do it. I also think I understand the difference between x++; and ++x; If I'm reading it right it means that the calculation will happen after and the other will happen before. Just not sure how to correct --x; using JSLint. Any help is greatly appreciated.

Thanks
Mardonis
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: JSLint Error help

Post by Jackolantern »

You are right. x++ will execute the line of code that the statement appears on with the old value and then increment x before the next instruction is executed. ++x will first increment the value, and then run the line of code that the statement appears on.

Not using those unary operators is a problem I have with JSLint, and depending on the implementation, I believe you can turn it off. I have not heard a good reason why to not use it. The best I have heard is that it can be unclear and can be a source of errors if you don't understand the difference between the postfix and prefix operators, but if you do, why not use it?

As for how to get by without it, 1 += x definitely doesn't work since with any assignment operator, the grammar only works as [identifier] = [statement or value] and can't work the other way around. The only way to do it without the operators is to do it arithmetically:

Using the postfix operator:

Code: Select all

var myValue = lives++;
...would become:

Code: Select all

var myValue = lives;
lives += 1;
Using the prefix operator:

Code: Select all

var myValue = ++lives;
...would become:

Code: Select all

var myVale = lives + 1;
Due to assignment having a very low operator precedence, the + will occur before the assignment every time.
The indelible lord of tl;dr
Mardonis
Posts: 139
Joined: Wed Jun 29, 2011 7:54 pm

Re: JSLint Error help

Post by Mardonis »

Ok, I get it it now. Thank you for the clarification on this problem I've been struggling with.
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: JSLint Error help

Post by Jackolantern »

No problem :)
The indelible lord of tl;dr
Post Reply

Return to “Coding”