Is there a better way of writing v = (v == 0 ? 1 : 0);

Viewed 74454

I want to toggle a variable between 0 and 1. If it's 0 I want to set it to 1, else if it's 1 I want to set it to 0.

This is such a fundamental operation that I write so often I'd like to investigate the shortest, clearest possible way of doing it. Here's my best so far:

v = (v == 0 ? 1 : 0);

Can you improve on this?

Edit: the question is asking how to write the above statement in the fewest characters while retaining clarity - how is this 'not a real question'? This wasn't intended to be a code-golf exercise, though some interesting answers have come out of people approaching it as golf - it's nice to see golf being used in a constructive and thought-provoking manner.

31 Answers

Well, As we know that in javascript only that Boolean comparison will also give you expected result.

i.e. v = v == 0 is enough for that.

Below is the code for that:

var v = 0;
alert("if v  is 0 output: " + (v == 0));

setTimeout(function() {
  v = 1;
  alert("if v  is 1 Output: " + (v == 0));
}, 1000);

JSFiddle: https://jsfiddle.net/vikash2402/83zf2zz0/

Hoping this will help you :)

v = Number(!v)

It will type cast the Inverted Boolean value to Number, which is the desired output.

v = !v * 1

multiplying by 1 to turn boolean into number

Related