Shorthand Addition Operator together with Shorthand If/Else - Javascript

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

Answers (3)

ZER0
ZER0

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

Matt Urtnowski
Matt Urtnowski

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

gion_13
gion_13

Reputation: 41533

You could use something like this:

number += 1 * (condition ? 1 : -1);

Upvotes: 4

Related Questions