I'd like to implement this:
//foo is a boolean
if(foo){
count++;
} else {
count--;
}
How could I write this with a one liner?
I'd like to implement this:
//foo is a boolean
if(foo){
count++;
} else {
count--;
}
How could I write this with a one liner?
foo ? count++ : count--;
This is called a ternary operator, see Operator precedence with Javascript Ternary operator
Simplest explaination is:
if this ? then this : else this
Using short-circuit evaluation and javascripts dynamic typing this should be the shortest:
count += foo || -1;
Simplest is to keep the logic you have now and convert to a ternary:
count += foo ? 1 : -1;
You can treat foo
as a number, specifically 1
or 0
:
count += 2 * foo - 1;
count = (foo) ? count+1 : count-1;
Please try this:
foo ? count++ : count--;