Coercions are useful and almost intuitive, but beware of pitfalls.
Consider below block of code -
|
|
Numbers greater than 0
and not undefined
are generally considered truthy
.
So, following is understandable -
|
|
But, you will be surprised if you do this -
|
|
This seems counterintuitive to the previous test that did not use an explicit true
check.
The reason is simple. While the first comparison simply checked whether 42
is truthy (it is), the next code block compared the int
42
with Boolean
true
.
When numbers and booleans are compared, booleans are coerced to numbers (true
= 1
) and compared. So, the results is false
.
Another way of looking at this problem -
|
|
How can we solve this problem correctly?
Simple - just make conversions explicit before a comparison.
|
|