Wednesday, May 30, 2012

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

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.

Source: Tips4all


  1. You can simply use:

    v = 1 - v;

    This of course assumes that the variable is initialised properly, i.e. that it only has the value 0 or 1.

    Another method that is shorter but uses a less common operator:

    v ^= 1;


    To be clear; I never approached this question as code golf, just to find a short way of doing the task without using any obscuring tricks like side effects of operators.

  2. Since 0 is a false value and 1 is a true value.

    v = (v ? 0 : 1);

    If you are happy to use true and false instead of numbers

    v = !v;

    or if they must be numbers:

    v = +!v; /* Boolean invert v then cast back to a Number */

  3. v = (v + 1) % 2 and if you need to cycle through more values just change 2 for (n + 1). Say you need to cycle 0,1,2 just do v = (v + 1) % 3.

  4. You could write a function for it and use it like:

    v = inv(v)

  5. If you don't care about any possibility other than 1:

    v = v ? 0 : 1;

    In the above case, v will end up being 1 if v is 0, false, undefined or null. Take care using this kind of approach - v will be 0 even if v is "hello world".

  6. Lines like v = 1 - v, or v ^= 1 or v= +!v will all get the job done, but they constitute what I would refer to as hacks. These are not beautiful lines of code, but cheap tricks to have the intended effect. 1 - v does not communicate "toggle the value between 0 and 1". This makes your code less expressive and introduces a place (albeit a small one) where another developer will have to parse your code.

    Having instead a function like v = toggle(v) communicates the intent at the quickest glance.

  7. You could do

    v = Math.abs(--v);

    The decrement sets the value to 0 or -1, and then the Math.abs converts -1 to +1.

  8. If it must be the integer 1 or 0, then the way you're doing it is fine, though parentheses aren't needed. If these a are to be used as booleans, then you can just do:

    v = !v;