Proper use of ||

It returns the item on the left if and only if it is truthy.

The following are not truthy:

  • The primitive boolean value false
  • The primitive string value "" (the empty string)
  • the numbers +0, -0 and NaN
  • the primitive value null
  • the primitive value undefined

Everything else is truthy.

Here is the list on the language specification.

In your case cache[0] returns 0 which as we can see is falsy so it enters recursion. This is why we avoid || for short circuiting in these situations.

You should consider checking directly that the object has that property: number in cache is one such way and another is cache[number] !== undefined.

Leave a Comment