Reputation: 5981
is it possibile to use the shorthand of addition/subtraction operator number += 1
and the shorthand of if / else number = (true ? 1 : 0);
together?
The condition should decide the addition or the subtraction.
Such like this: number = (true ? +=1 : -=1);
Upvotes: 1
Views: 2813
Reputation: 25332
If you want to use the +=
operator you need to have the variable declared in first place, otherwise can't work. If you have it, then you can simple have:
number += condition ? 1 : -1;
Notice that if you have just the number 1
and -1
, and condition
is boolean, you could do something like:
number += +condition || -1;
To be precise, something that returns 1
for true
and something else for false
.
Upvotes: 1
Reputation: 2566
This should work and have the effect of adding or subtracting an operation
var number = 0;
number += (condition) ? (1 * (<operation>)) : (-1 * (<operation>));
Upvotes: 0
Reputation: 41533
You could use something like this:
number += 1 * (condition ? 1 : -1);
Upvotes: 4