Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Other ways to increment a variable in JavaScript [duplicate]

Tags:

javascript

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

I'm a big fan of Douglas Crockford and his excellent book, JavaScript: The Good Parts. I also use his JSLint tool on an hourly basis before checking in any code to our repository, as is good sense.

One thing I've noticed when running code through JSLint is its insistence that the ++ increment operator is somehow evil. I know I can turn certain rules off, but that's cheating ;). Crockford mentions his dislike on page 112 of JS: TGP...

In my own practice, I observed that when I used ++ and --, my code tended to be too tight, too tricky, too cryptic. So, as a matter of discipline, I don't use them any more. I think that as a result, my coding style has become cleaner.

That's all very lovely, but he doesn't give any examples of the way he codes them now. I assume he's doing something like...

var i;
i = 0;
i = i + 1;

Again, great, but I've got a few basic 'for loops' in my JS code, as I imagine many people have, and I've always used the standard syntax...

for (i = 0; i < myArray.length; i++) { 
    // Loop Stuff 
}

Am I missing something? What's the cleanest and/or best way to increment/decrement?

like image 626
Daniel Attfield Avatar asked Jul 06 '11 09:07

Daniel Attfield


People also ask

How do you increment a variable in JavaScript?

JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.

What is i ++ in JS?

The value i++ is the value of i before the increment. The value of ++i is the value of i after the increment. Example: var i = 42; alert(i++); // shows 42 alert(i); // shows 43 i = 42; alert(++i); // shows 43 alert(i); // shows 43. The i-- and --i operators works the same way.

What is the opposite of ++ in JavaScript?

JavaScript Increment ++ and Decrement -- The increment and decrement operators in JavaScript will add one (+1) or subtract one (-1), respectively, to their operand, and then return a value.


1 Answers

I think this is rather controversial, and I personally stick to i++ in loops. Of cource, you can replace it with i = i + 1 in your loop statement, to be fully compliant to JSLint.

There aren't real alternatives to increment and decrement numerical values in JavaScript. You can often use Array.forEach() and/or Object.keys() in order to prevent numerical indexes.

like image 136
b_erb Avatar answered Oct 14 '22 15:10

b_erb