Interval Comparison Doesn't Bomb In Js
Solution 1:
Because JavaScript allows implicit type coercion, in this case from boolean to number. The -1 < x
results in a boolean, which is then implicitly coerced to a number (true = 1, false = 0) for the (result) < 1
part. So:
When
-1 < x
is false, the second part is0 < 1
which is true.When
-1 < x
is true, the second part is1 < 1
which is false.
This is covered in the abstract relational comparison algorithm in the spec, and the various operations it links to.
-1 < x < -1is always false-2 < x < 2is always true
In the last 2 cases it seems it is just comparing the 2 ends of the expressions. How are those expressions evalued?
Using x = -1
and x = 1
:
- If
x = -1
, then-1 < x
is false, so the rest is0 < -1
, which is false. - If
x = 1
, then-1 < 1
is true, so the rest is1 < -1
which is false. - If
x = -1
, then-2 < -1
is true, so the rest is1 < -2
, which is false. - If
x = 1
, then-2 < 1
is true, so the rest is1 < -2
which is false.
Solution 2:
I think that this happens because javascript implicitly considers true
to have the value 1
and false
to have the value 0
.
When you do -1 < x < 1
, what you're actually doing is (-1 < x) < 1
, or true < 1
if x = 0
which is false
.
However, if x=-2
, (-1 < x < -1)
will return true
as false < 1
is true
. Hope this helps.
You can read more about this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators
Solution 3:
The reason is that JS interprets your expression.
if((-1 < x) < 1) {
console.log('x: ', x)
}
Trying using braces...
Post a Comment for "Interval Comparison Doesn't Bomb In Js"