Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are increment/decrement operators considered bad form in Javascript? [duplicate]

Possible Duplicate:
Why avoid increment ("++") and decrement ("--") operators in JavaScript?

I've recently been running all my javascript through JSLint and it always gives me Unexpected '++' on my increment operators. I've also noticed there is a JSLint option to tolerate ++/--.

Is it considered bad form to use i++/i--?

like image 891
Brandon Cordell Avatar asked Feb 24 '23 03:02

Brandon Cordell


1 Answers

If I understand correctly, the reason it's in JSLint is because there's a significant difference between ++i and i++, and many developers don't necessarily appreciate the implications of being specific about when the addition is done, in relation to other operations around it.

for example:

var i = 0;
if(i++) {
    //does this get run or not?
}
if(--i) {
    //and what about this one?
}

This is why Crockford considers it bad practice, and prefers the more explicit +=1.

However, in general, I don't have this kind of issue with ++; I'm perfectly happy to use it, and I would ignore JSLint telling me not to (most of the time!).

This is the important thing about JSLint -- it doesn't tell you about actual errors; everything it tells you is a suggestion. Some of them are excellent suggestions (eg you should never ever use with); some are good suggestions that indicate poor code; and some of them are only a problem some of the time and should be considered individually. As a developer it is more important that you need to know why it's making its suggesting than it is to actually fix them. Once you understand the reasons for them being pointed out, you are in a position to decide for yourself whether a given instance of it in your code is a problem or not and how to fix it.

Hope that helps.

like image 90
Spudley Avatar answered Feb 25 '23 17:02

Spudley