32

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
  • 24,114
  • 8
  • 78
  • 84
chtenb
  • 13,449
  • 12
  • 67
  • 110

5 Answers5

32

There is no shorter way than what you currently have.

alex
  • 460,746
  • 196
  • 858
  • 974
  • 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
  • 1
    @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
12

You can do this:

foo ^= 1

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

Sjoerd
  • 71,634
  • 16
  • 123
  • 171
3
var value = true;
alert(value);
value ^= true;
alert(value);​

You could get 1 or 0 here

Anujith
  • 9,319
  • 6
  • 32
  • 47
-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,340
  • 1
  • 12
  • 30
-3

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