+ 1

Please why does this code only work with fib sequence 1?

A recursion based code returning the first 10 numbers of the fibonacci sequence.Only works when I enter the values of num and array during function declaration,but doesn't work if I rearrange it with code in fib sequence 2 and Fibonacci sequence 3 https://code.sololearn.com/WkOvCJ6tRnDn/?ref=app https://code.sololearn.com/W0B90pLH9BYm/?ref=app https://code.sololearn.com/Wd5EeG85skr4/?ref=app

28th Aug 2022, 8:30 PM
steve Purpose
steve  Purpose - avatar
5 Réponses
0
All three of your examples are working as they should. Looking at 'fib sequence recursion 1', the function fib parameters (num, array) are assigned values that act as defaults. If the function was invoked without passing any values, fib(), the function will use the default values to run the code block. But in this case, the fib function is passed a value of 10 thus overriding the default of num parameter. Looking at the two other code examples you provided if you assign the 10 to the constant num you will get the output you expected. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
29th Aug 2022, 12:55 PM
ODLNT
ODLNT - avatar
0
ODLNT I tried them and they worked ,but the whole function no longer makes sense to me..why did he also write Const[nextTolast,Last]? If you can rewrite the code with comments by the side I'll appreciate.
29th Aug 2022, 1:07 PM
steve Purpose
steve  Purpose - avatar
0
ODLNT I've gone through the code..But please where does line 24 come in num=num-1.I don't get that part Also is from line 19 is the else part to the if statement ?
1st Sep 2022, 4:06 PM
steve Purpose
steve  Purpose - avatar
0
steve Purpose Fib's first parameter, num, keeps track of how many times the function has been invoked/ recursed. In this case, num=num-1 is counting down from the initial value of 10. Thus, once num is less than 2, the recursion stops and the resulting value is returned in the if statement. And finally, else is a part of the if statement. https://www.w3schools.com/js/js_if_else.asp
2nd Sep 2022, 12:58 AM
ODLNT
ODLNT - avatar
0
I know what a conditional is..I just wanted more clarification on your code considering I didn't see the else..so that means we used.array.slice(-2) and not array.slice( 0,-1) if you understand what I mean from your code
2nd Sep 2022, 3:24 AM
steve Purpose
steve  Purpose - avatar