I'm trying to shorten out the following code:
var a = 0, b = 0;
function() {
return a === 0 && b === 0; // returns 'true'
}
So, I thought something like the following would do:
var a = 0, b = 0;
function() {
return a === b === 0; // returns 'false'
}
Initially, I thought that such syntax would throw an error, but apparently it returns false
. Why does a === b === 0
return false
?
The expression a === b === 0
is interpreted as if it were written (a === b) === 0
. The result is false
because (a === b)
gives true
, and true
is not ===
to 0
.
One can imagine a programming language that would understand a chain of expressions connected by ==
or ===
or whatever, meaning that all values should be compared in one big "group equality" comparison. JavaScript is not such a language, however.
This is due to how operators are evaluated. In JavaScript, equality operators are evaluated left-to-right (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
This means that this:
a === b === 0
Becomes this after one step:
true === 0
Since the number zero is not equal to the boolean true, your expression returns false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With