-1

Given boolean value completed = false how do I flip it back and forth? I could of course do something like this:

if (completed) {
    completed = false
} else {
    completed = true
}

But that feels hacky and too long. Is there any slick and cleaner way of doing this? Thanks.

Contradictions
  • 137
  • 3
  • 15

1 Answers1

1

Assuming you declared variable with let or var, so that you can reassign the value :

completed = !completed

spurushottam13
  • 86
  • 2
  • 11
  • What does `let` or `var` have to do with it? – Ivar Jul 05 '21 at 21:25
  • Could be a function argument also – charlietfl Jul 05 '21 at 21:27
  • @Ivar if you don't use `let` or `var` and use `const` then you are not allowed to reassign the variable. – spurushottam13 Jan 17 '22 at 11:52
  • I see what you mean now. That might be worth to mention explicitly. You can also not declare your variable at all (it becoming an implicit global variable), in which case `completed = !completed` will still work without any issue. (Hence my previous question.) – Ivar Jan 17 '22 at 12:34