2

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;
3
  • 1
    No, there's no compound assignment for boolean operations in JS. So yes, you have to use x = x && y form. Commented Feb 4, 2016 at 10:49
  • It's worth nothing that true & true == true, true & false == false and false & false == false - they might not be boolean values, but the equality holds. Commented Feb 4, 2016 at 10:50
  • Ok but for example, I used this: $("...").toggleClass("myclass",test) and test was not recognized as boolean and the behaviour of toggleClass was different than expected. This is why I would liketo know if exists the real boolean assignment. In my case I solve with the double exclamation mark to cast it to boolean $("...").toggleClass("myclass",!!test) Commented Feb 4, 2016 at 10:53

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.