To understand the below Fibonacci calculator, I wonder how the following return statement with assignment works:
let a = 0;
function foo (b) {
if (b === 20) return 1;
else return a = foo(b+1) + foo(b+1);
}
Which gives the following results:
foo(15)
>> 32
a
>> 32
foo(18)
>> 4
a
>> 4
foo(19)
>> 2
a
>> 2
foo(10)
>> 1024
a
>> 1024
What is the exact behaviour of the assignment, and why do the values of a become multiples of 2?
This can possibly also explain why this works for calculating Fibonacci:
const fib = (n, dp) => {
dp = dp || {};
if (dp[n]) return dp[n];
if (n === 1) return 1;
if (n === 0) return 0;
return dp[n] = fib(n - 1, dp) + fib(n - 2, dp);
};
>Solution :
return a = foo(b+1) + foo(b+1) is a return statement. On the right-hand side of return here is an assignment expression (a = foo(b+1) + foo(b+1)).
The value of an assignment expression identifer = right-hand-side-expression is the result of evaluating the right-hand side expression, here: foo(b+1) + foo(b+1).
So we can now describe what is happening: foo(b+1) + foo(b+1) is evaluated first and results in a value. This value is assigned to a using the assignment operator =. The result of this expression is then also returned.
Why the code is doing this, I do not know. It might be for convenient inspection while debugging the code.
function foo (b = 0) {
if (b === 5)
return 1
else
return foo(b+1) + foo(b+1)
}
console.log(foo())