Proper use of ||

前端 未结 3 1097
故里飘歌
故里飘歌 2020-12-03 23:04

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

相关标签:
3条回答
  • 2020-12-03 23:49

    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.

    Edit:

    Yes, the value has to be truthy...not only true.

    0 讨论(0)
  • 2020-12-03 23:50

    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.

    0 讨论(0)
  • 2020-12-03 23:54

    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.

    0 讨论(0)
提交回复
热议问题