This page looks best with JavaScript enabled

Coercions can be counter-intuitive, use same-type comparisons

 ·   ·  ☕ 1 min read

Coercions are useful and almost intuitive, but beware of pitfalls.

Consider below block of code -

1
const x = 42;

Numbers greater than 0 and not undefined are generally considered truthy.

So, following is understandable -

1
2
if (x) console.log("found the answer");
// found the answer

But, you will be surprised if you do this -

1
2
if (x == true) console.log("found the answer");
// nothing

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 -

1
2
3
4
5
const x = 42;
const answer = true;

console.log(x == answer);
// false

How can we solve this problem correctly?

Simple - just make conversions explicit before a comparison.

1
2
3
4
5
const x = 42;
const answer = true;

console.log(Boolean(x) == answer);
// true
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things