Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript increments [duplicate]

Possible Duplicate:
++someVariable Vs. someVariable++ in Javascript

I know you can add one to a variable simply by doing i++ (assuming i is your variable). This can best be seen when iterating through an array or using it in a "for" statement. After finding some code to use online, I noticed that the for statement used ++i (as apposed to i++).

I was wondering if there was any significant difference or if the two are even handled any differently.

like image 426
Freesnöw Avatar asked May 16 '11 16:05

Freesnöw


People also ask

What is++ a in JavaScript?

The Complete Full-Stack JavaScript Course! ++a returns the value of an after it has been incremented. It is a pre-increment operator since ++ comes before the operand. a++ returns the value of a before incrementing. It is a post-increment operator since ++ comes after the operand.

How to increment a variable js?

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.

Can JavaScript set have duplicate values?

The Set object lets you store unique values of any type, whether primitive values or object references. you are passing new object not reference so it is allowing to add duplicate.


2 Answers

Yes there is a big difference.

var i = 0;

var c = i++; //c = 0, i = 1
    c = ++i; //c = 2, i = 2
    //to make things more confusing:
    c = ++c + c++; //c = 6
    //but:
    c = c++ + c++; //c = 13

And here is a fiddle to put it all together: http://jsfiddle.net/maniator/ZcKSF/

like image 163
Naftali Avatar answered Oct 16 '22 08:10

Naftali


The value of ++i is i + 1 and the value of i++ is just i. After either has evaluated, i is i + 1. It's a difference in timing, which is why they're often called 'pre-increment' and 'post-increment'. In a for loop, it rarely matters, though.

like image 41
Rafe Kettler Avatar answered Oct 16 '22 08:10

Rafe Kettler