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?
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:This is shorter than having to check one, then the other:
There is no
&&=operator, as using short circuit evaluation in that case doesn’t make sense.