Problem understanding challenge question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Problem understanding challenge question

Hello, could someone help me understand this code: function fib(num) { if(num <= 2) { return 1; } return fib(num - 1) + fib(num - 2); } document.write(fib(6)); In this code, is the function actually calling itself until the condition is true? Why is the actual result 8? Thanks in advance.

11th Jun 2021, 6:58 AM
David
David - avatar
3 Answers
+ 3
https://youtu.be/VtG0WAUvq2w have a look at this .. after that you will be able to solve it by yourself 🙂 .. leme know if you need further help.
11th Jun 2021, 7:02 AM
Prashanth Kumar
Prashanth Kumar - avatar
+ 2
if num<=2 return 1, so fib(1) = 1, fib(2) = 1 now: fib(3) return fib(2)+fib(1) = 1+1 = 2 fib(4) return fib(3)+fib(2) = 2+1 = 3 fib(5) return fib(4)+fib(3) = 3+2 = 5 fib(6) return fib(5)+fib(4) = 5+3 = 8
11th Jun 2021, 12:16 PM
visph
visph - avatar
+ 1
Thanks a lot for your help, Prashanath! I will look the video
11th Jun 2021, 7:05 AM
David
David - avatar