Ground Zero

In some languages, and by some I probably mean JavaScript, values are tested for truthiness. Any value can be treated as a boolean.

This gives us a special case with zero.

Consider this:

if ( && < {

The above is probably ensuring that there’s a value for and then testing that it’s off screen… but is it really doing that?

By testing this with an element at screen position zero with the viewport starting at 0, we might discover that the logic behaves in an unexpected way.

While it’s important to test things with realistic looking numbers, we can often forget that there’s an important edge case lurking at zero when there’s also falsy as a concept in our programming language. This is as much a test failure as an implementation gotcha.

In a recent bug, I had the following typescript:

if (element?.top && element?.top < {

It looks like a more convincing test for the element not being null/undefined than the previous test for the top not being defined… but… when top === 0 then this code === goes wrong.

The correct implementation should have been:

if (element && element?.top < {

But it was the test case that was most important. We should definitely have remembered to test with the value zero.

Sometimes ZERO === EVERYTHING!

One comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s