Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JavaScript allow both && (logical) and & (bitwise) in conditional statements?

I recently found a piece of javascript which was evaluating null / undefined like so:

// The single & is on purpose!
if(x !== null & x !== undefined) {
    // Do this...
}

This looks like a very bad practice to me, but it seems to work.

As far am I am aware, these operators are supposed to perform two different tasks:

var x = 3; x &= 6; // No syntax errors.

var x = 3; x &&= 6; // Syntax error.

if(x == null && x == undefined) // No syntax errors.

if(x == null & x == undefined) // No syntax errors, but wrong operator usage?

Can anyone shed some light on this please?

like image 807
Matthew Layton Avatar asked Jun 24 '26 02:06

Matthew Layton


2 Answers

When used like that, both the operators & and && work as logical operators (even if the & operator isn't actually a logical operator). The practical difference is that && uses short circuit evaluation, and & doesn't.

There is no problem using the & operator, as long as it's possible to evaluate the second operand even if the first operand evaluates to false.

The && operator can be used to keep the second operand from being evaluated, when the first operand determines if the second operand is possible to evaluate. For example:

if (x != null && x.prop == 42) { ... }

This is shorter than having to check one, then the other:

if (x != null) {
  if (x.prop == 42) { ... }
}

There is no &&= operator, as using short circuit evaluation in that case doesn't make sense.

like image 65
Guffa Avatar answered Jun 26 '26 16:06

Guffa


expr1 & expr2 casts both arguments are cast to integers, then computes their bitwise AND. In case of booleans, the result is either 0 or 1 (NOT false or true). Zero is falsy and one is truthy, but there's still a difference in that both arguments are always evaluated.

expr1 && expr2 returns expr1 if it is falsy, otherwise it evaluates and returns expr2. Expr2 is not evaluated if expr1 is falsy.

like image 39
John Dvorak Avatar answered Jun 26 '26 15:06

John Dvorak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!