34

How can I flip the value of a boolean variable in javascript, without having to include the variable name twice? So

foobarthings[foothing][barthing] = !foobarthings[foothing][barthing];

without writing foobarthings[foothing][barthing] twice.

Lesmana
  • 25,663
  • 9
  • 82
  • 87
chtenb
  • 14,924
  • 14
  • 78
  • 116

6 Answers6

32

There is no shorter way than what you currently have.

alex
  • 479,566
  • 201
  • 878
  • 984
  • that's not entirely true, there is such thing as the `not` operator: `ver inverse = return !foo;` that's completely valid – J-Cake Jul 13 '18 at 03:32
  • 2
    @JacobSchneider The code you posted isn't syntactically valid and the OP already demonstrates knowledge of the `!` operator. – alex Jul 13 '18 at 12:10
  • Anujith Answered with `^=` operation, why do you think that's not valid? – Pixsa Jan 06 '23 at 19:50
13

You can do this:

foo ^= 1

But this really switches foo between 0 and 1, not true and false.

Sjoerd
  • 74,049
  • 16
  • 131
  • 175
3
var value = true;
alert(value);
value ^= true;
alert(value);​

You could get 1 or 0 here

Anujith
  • 9,370
  • 6
  • 33
  • 48
0

you can create a new constructor with a boolean property and then add a prototype to flip that

function Bit(bit=false) {
  this._ = bit;
}
Bit.prototype.flip = function() {
  this._ = !this._;
  return this._
}

//example:
var foo = new Bit();
console.log(foo._) //logs false
foo.flip() //flips to true
console.log(foo._); //logs true
console.log(foo.flip()) //flips to false and logs it
Rubys wolf
  • 118
  • 6
-1

To flip the value of a boolean variable in JS you need the syntax like this:

return !foo;

It's really that easy...

Or you can do (foo ^= 1) == true (must be == not ===)

J-Cake
  • 1,526
  • 1
  • 15
  • 35
-3

You can have just foo and !foo in the place where you execute it or check the condition.