Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ++ and +=1 in javascript

Could somebody explain why the following functions give different results. The first does not seem to work, but the second does. I'm puzzled because I thought +=1 and ++ did the same thing.

(I'm not intending to actually use this code, it's just to demonstrate the difference).

/*function 1*/ function incrementIfZero1(base,element) {      if (element == 0) {         return base++;     }     else     {         return base;     } };   /*function 2*/ function incrementIfZero2(base,element) {      if (element == 0) {         return base+=1;     }     else     {         return base;     } };  incrementIfZero1(1,0) /* -> 1*/ incrementIfZero2(1,0) /* -> 2*/ 

Any help is very much appreciated.

Thanks,

Robin

[Edit:]

Thank you for your replies, it makes sense now. I had also tried the following statement, which resulted in the same thing as function 1:

return (base++) 

I'm now surprised that this doesn't give the same result as function 2 - I would have expected the brackets to 'force' it to be evaluated before returning. Any idea why this is not the case?

like image 201
RobinL Avatar asked Jun 21 '13 18:06

RobinL


People also ask

What is the difference between += 1 and ++ in JS?

++ increases the integer by one and += increases the integer by the number of your choice.

What is the difference between 1 and 1 in JavaScript?

There is no difference between the numbers 01 and 1 . They are absolutely identical. There is a difference between the strings "01" and "1" .

Is ++ i the same as i += 1?

The expression ++i is equivalent to (i += 1). The value of both expressions is i after the increment has been performed.

What is the difference between += and =+ in JavaScript?

The + sign before the function, actually called Unary plus and is part of a group called a Unary Operators and (the Unary Plus) is used to convert string and other representations to numbers (integers or floats). A unary operation is an operation with only one operand, i.e. a single input.


1 Answers

when you return base++ it returns the value of base just before it gets incremented. You want to do ++base to make sure the increment happens first then it gets returned

otherwise ++ is the same as +=1

[edit] in response to your edit, i tried wrapping random statements in parentheses and most mathematical operators respond as expected, this incrementation seems to be exempt, likely because the syntax of pre-incrementation vs post-incrementation is highly intentional and the statement itself returns a specific value regardless of whether or not you wrap it in parentheses

like image 134
Stephan Avatar answered Sep 23 '22 07:09

Stephan