This page looks best with JavaScript enabled

Null check gotchas

 ยท   ยท  โ˜• 1 min read

Beware of these null check gotchas.

Consider this code -

1
2
3
4
5
6
7
const sum = null;

if (sum) {
  console.log("valid sum");
}

// nothing printed

The above code shows expected behaviour. Nothing is printed since if(sum) returns false.

Now, try the code below.

1
2
3
4
5
if (sum >= 0) {
  console.log("valid zero or positive sum");
}

// valid zero or positive sum

It can throw off your calculations by a wide margin.

Strange but true null >= 0.

But, null > 0 and null == 0 both return false.

To work-around the problem always use the comparison directly in if statement or do an explicit Boolean conversion before the comparison.

Stay in touch!

Tech in your inbox - news, tips, and summary of our posts. 2 emails per month.

Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things