Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does return statement with assignment work for calculating Fibonacci number

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading