Ad

Shorthand Assignment Operator For Inverting Boolean

- 1 answer

There are shorthand operators for the basic arithmetic operators, such as:

x = x+2;
x += 2;

or

y = y*2;
y *= 2;

However, I was wondering if there was any such operator that could simply invert the value of a boolean.

For example, assuming z = true, is there any shorter equivalent to:

z = !z;

I know it can't be just !z, because then it would just return the opposite value of z, but it wouldn't change its value.

I know I'm kind of lazy, but I use this a lot in my code and am trying to optimize it as much as possible. I'd try to avoid repeating variable names as much as possible to keep it cleaner and more elegant.

Also, I'm coding in JavaScript.

Ad

Answer

Personally I would just negate the thing the way you've done it. But if it really matters to you, and you can afford to forgo the boolean type, just use the numeric internal representation (true==1, false==0) and bitwise operators to negate it:

z = true;  // z is type boolean
z ^= 1;    // z is now false, but its type is number
           // (z == false) evaluates to true and you can still do things like if (z)...
z ^= 1;    // z is now true again
Ad
source: stackoverflow.com
Ad