Page 1 of 1

JSLint Error help

Posted: Thu Oct 02, 2014 7:02 pm
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

Re: JSLint Error help

Posted: Fri Oct 03, 2014 2:13 am
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.

Re: JSLint Error help

Posted: Fri Oct 03, 2014 12:56 pm
by Mardonis
Ok, I get it it now. Thank you for the clarification on this problem I've been struggling with.

Re: JSLint Error help

Posted: Fri Oct 03, 2014 5:40 pm
by Jackolantern
No problem :)