Tobia
Tobia

Reputation: 9506

Javascript boolean assignment

I found that in javascript &= operator is a bitwise assignement:

var test=true;
test&=true;
//here test is an int variable

Does boolean assignment exist in javascript?

Is this the only solution?

var test=true;
test=test & true;

Upvotes: 2

Views: 1611

Answers (2)

Peter
Peter

Reputation: 3008

As of 2020, there are logical AND and logical OR assignment operators &&= and ||=:

var test = true;
test &&= true;

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND_assignment

Upvotes: 1

Vistari
Vistari

Reputation: 707

There isn't a shorthand assignment for booleans so yes you would have to use your outlined solution.

var test=true;
test=test & true;

This could largely be down to the short-circuiting that occurs with Boolean operations such as with the && operator. If the first value in the && statement is false then it will short circuit and not check any further. That behaviour might not be obvious to everyone so they may have deliberately left out this operator to prevent confusion.

Upvotes: 1

Related Questions