Click here to Skip to main content
15,917,586 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was just wondering, is there a shorthand version of the following?
myBool = !myBool;

I'm asking because this way I have to enter the variable twice.

Thanks.
Posted
Updated 3-Nov-22 16:20pm
v2

You do a read and a write to the same variable but it won't get any shorter than the code you already got. With addition for example it would be:
myInt += myInt 

or
myInt++ 

to add one.

When you apply this in javascript with a bool, like this:
C#
var x = true;
x++;

it simply will become 2, so the data type has changed. In c/c++ it would be possible to create such a friend operator... but for javascript this isn't possible.

Good luck!
 
Share this answer
 
v2
Comments
pimb2 9-Nov-10 12:28pm    
Okay thanks. By the way, doesn't myInt += myInt double the value instead of adding one?
E.F. Nijboer 9-Nov-10 13:06pm    
Yes, but because myInt != myInt doesn't really make any sense I took that as an example.
Usually, you invert a bool because you are going to be using it somewhere with its inverted state. Rather than inverting the bool and assigning it back to itself, just use the inverted version elsewhere. So instead of this:
JavaScript
myBool = !myBool;
someFunction(myBool);

Do this:
JavaScript
someFunction(!myBool);

Of course, that doesn't make sense if you have something like this:
JavaScript
if(someCondition) {
    myBool = !myBool;
}
// Lots of code that uses myBool.

In that case, just suck it up and type the massive amount of code required to invert the bool. :rolleyes:
 
Share this answer
 
if you create your own constructor that lets you access a boolean then you can flip it with only one reference:
JavaScript
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
 
Share this answer
 
Comments
Richard Deeming 4-Nov-22 4:48am    
Except you can't - you still have to reference the variable twice on the line that's actually flipping the variable:
this._ = !this._

All you've done is add a load of extra code for no real benefit.

And you're using an optional parameter, which wasn't available when the question was posted; but you've decided not to use a proper class[^], which would be the proper way to do it in modern Javascript.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900