0

I'm studying recursion, and I came across an example of using the Fibonacci sequence and it talked about the concept of memoization. In that, it has a variable that is declared with an OR (||). I'm a little confused by that.

Here is the code:

fib = (number, storage) => {
    storage = storage || {}; //<--This is what I'm asking about

    if (storage[number]){
        return storage[number];
    } 
    if (number <= 1){ //<--second question 
        return 1;
    } 
    return storage[number] = fib(number -1, storage) + fib(number-2, storage);
}

Is my understanding correct that when this is called the first time, it assigns an empty object to storage, since storage isn't passed in the first time, and doesn't yet exist? Then on subsequent calls, since storage is something (an object), it just goes with the first option and assigns storage and ignores the OR?
Also, separate question, but as this function doesn't explicitly stop at 0, why does it in fact stop at zero? Why doesn't it just continue indefinitely into negative numbers?

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
Primitive
  • 11
  • 2
  • 1) Yes, 2) Because `0` is less-than `1` – Phil Apr 13 '23 at 23:59
  • the Fibonacci sequence was "invented" in the 12th century; in Occident where the existence of negative numbers were not discovered until the 16th century ->The Fibonaci sequence can only be conceivable with positive values... – Mister Jojo Apr 14 '23 at 00:12

0 Answers0