chtenb
chtenb

Reputation: 16204

Shorthand for flipping a boolean variable

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.

Upvotes: 35

Views: 21333

Answers (6)

Rubys wolf
Rubys wolf

Reputation: 128

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

Upvotes: 0

J-Cake
J-Cake

Reputation: 1638

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 ===)

Upvotes: -1

Sjoerd
Sjoerd

Reputation: 75679

You can do this:

foo ^= 1

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

Upvotes: 13

Anujith
Anujith

Reputation: 9370

var value = true;
alert(value);
value ^= true;
alert(value);​

You could get 1 or 0 here

Upvotes: 3

Arunkumar Srisailapathi
Arunkumar Srisailapathi

Reputation: 1169

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

Upvotes: -3

alex
alex

Reputation: 490607

There is no shorter way than what you currently have.

Upvotes: 33

Related Questions