DEV Community

Cover image for Falsey values and -1 returns
Nick Salvatore
Nick Salvatore

Posted on

Falsey values and -1 returns

This has happened to me a lot, so I thought it was worth reflecting on. I came across a Leetcode problem this morning that asks you to create a method for an array that returns the last item in the array. If the array is empty, return -1.

It’s a beginner-level problem, but the gotcha comes in considering falsey values like null or undefined.

Intuition

The intuition in solving this problem is to simply get the index of the last item using .length-1. If the item exists, return the item. Otherwise, return -1

This approach has one problem though which is that if the array contains falsey values like null or undefined, it will return -1

Don’t return -1 explicitly

These Leetcode problems arise pretty regularly where you need to return something in an array, otherwise you return -1.

There’s a strong intuition, at least for me, to check for some case and then explicitly return -1 if that case isn’t met. You’ll fail your tests and then see that since the last item you were trying to access is null, -1 was returned instead of null. Then you’ll add a check for null or undefined, but you’ll find that empty arrays also return undefined.

A sign that you are approaching the problem incorrectly is acting on this intuition to return -1 explicitly.

Derive -1 naturally

If an array is empty, calculating the index with .length-1 will return -1. So to solve the problem eloquently, all you need to do is check for an empty array. If the array is empty, return the index, otherwise return the item.

The code would look something like this.

Array.prototype.last = function() {
    const i = this.length-1

    if (i < 0) {
        return i
    }

    return this[i]
}
Enter fullscreen mode Exit fullscreen mode

The lesson

So again, if you don’t want to deal with the headache of failed Leetcode tests on simple af problems, which leave you feeling like more of an imposter than you already are (I'm projecting, you're probably great), make sure to consider falsey values and also be wary of explicit -1 returns.

Top comments (0)