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 this work:
var fibonacci = (function () {
var cache = [0, 1];
function fibonacci(number) {
return cache[number] = cache[number] || (fibnonacci(number - 1) + fibonacci(number - 2));
}
return fibonacci;
})();
var $div = $('div');
for (var index = 0; index < 10; index++) {
$('<span />').text(fibonacci(index))
.appendTo($div);
}
We use the symbol || to denote the OR operator. This operator will only return false when both conditions are false. This means that if both conditions are true, we would get true returned, and if one of both conditions is true, we would also get a value of true returned to us.
The && and || Operators in JavaScript. If applied to boolean values, the && operator only returns true when both of its operands are true (and false in all other cases), while the || operator only returns false when both of its operands are false (and true in all other cases).
The logical OR ( || ) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With