2

I'd like to implement this:

//foo is a boolean
if(foo){
    count++;
} else {
    count--;
}

How could I write this with a one liner?

Zac
  • 12,637
  • 21
  • 74
  • 122
wong2
  • 34,358
  • 48
  • 134
  • 179
  • 2
    Less code is not always better (unless your sole criterion for "better" is less code, which is not sensible). But in this case one of the offered ternary operations is likely best. – RobG Apr 27 '12 at 05:28

7 Answers7

11

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

Community
  • 1
  • 1
hkf
  • 4,440
  • 1
  • 30
  • 44
  • In ES5 it's called the *[conditional operator (?:)](http://es5.github.com/#x11.12)*, though it is generlly called a *ternary expression* or *ternary operation* – RobG Apr 27 '12 at 04:47
  • I like this one because it's both brief and clear and I think it's even easier to read than Nikhil's answer. I personally value clarity over brevity. If you ever spend significant time working on other people's code, you will value the clarity aspect too. – jfriend00 Apr 27 '12 at 04:52
9

Try this:

count += foo ? 1 : -1
Nikhil Baliga
  • 1,339
  • 12
  • 18
5

Using short-circuit evaluation and javascripts dynamic typing this should be the shortest:

count += foo || -1;
KooiInc
  • 119,216
  • 31
  • 141
  • 177
3

Simplest is to keep the logic you have now and convert to a ternary:

count += foo ? 1 : -1;

Andrew
  • 14,204
  • 15
  • 60
  • 104
1

You can treat foo as a number, specifically 1 or 0:

count += 2 * foo - 1;
Blender
  • 289,723
  • 53
  • 439
  • 496
  • 3
    Except this code is completely unreadable... – Travis Webb Apr 27 '12 at 04:28
  • The OP did ask for the "shortest" way (in the title of the question), not a short answer that was readable. Personally, I find hkf's answer to be the most readable which is probably how I'd do it as I value clarity over brevity (which is the case for anyone who's had to spend a lot of time working/fixing other people's code). – jfriend00 Apr 27 '12 at 04:50
0
 count = (foo) ? count+1 : count-1;
sgowd
  • 2,242
  • 22
  • 29
0

Please try this:

foo ? count++ : count--;
Wouter Dorgelo
  • 11,770
  • 11
  • 62
  • 80
sarwar026
  • 3,821
  • 3
  • 26
  • 37