Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of ||

Tags:

javascript

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);
}
like image 842
sircodesalot Avatar asked Aug 03 '13 18:08

sircodesalot


People also ask

What is || used for?

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.

Is || and && the same?

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).

What is use of || in JavaScript?

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.


1 Answers

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.

like image 122
Benjamin Gruenbaum Avatar answered Nov 03 '22 05:11

Benjamin Gruenbaum