The general question I suppose is: when does || return the item on the left, and when does it return the item on the right?
The specific question, is why doesn\'t t
It returns the first true
from the left. If no true
it returns false
. If the expressions resolve to true, in case of a Boolean or a non-zero or non-null or non-undefined value.
Yes, the value has to be truthy...not only true.
Your code doesn't work because you can't use the value in cache when it's 0 as 0 || func()
asks for the function to be called.
So it always call the second term for 0 and thus makes a stack overflow as the recursion has no end.
A solution would be to change your internal function like this :
function fibnonacci(number) {
if (number in cache) return cache[number];
return cache[number] = fibnonacci(number - 1) + fibonacci(number - 2);
}
As an aside please note the spelling of Fibonacci.
It returns the item on the left if and only if it is truthy.
The following are not truthy:
false
""
(the empty string)NaN
null
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
.