Fibinacci sequence in JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Fibinacci sequence in JavaScript

Hello there! As a challenge I try to solve the Fibonacci sequrnce using recursion in JavaScript. Can somebody please explain it to me on a very high level.

3rd Sep 2019, 1:09 PM
Crisse
Crisse - avatar
1 Answer
+ 2
Hi Crisse, In the following code I create the "var fibonacciFunction" that contain (or save) a function in it (fibonacci function). This function is recursive, so it will be called until a conditon is verified. In this case the exit condition is the "if (n===1)". Only when n is equal to 1 the function won't be called anymore. In the other case, the function will be called with the n-1 parameter (in this example the function runs 9 times): <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> Press F12 and check in the console! <script> var fibonacciFunction = function (n) { console.log("n is " + n); if (n===1) { console.log("EXIT"); return [0, 1]; } else { var s = fibonacciFunction(n - 1); s.push(s[s.length - 1] + s[s.length - 2]); return s; } }; console.log(fibonacciFunction(8)); </script> </body> </html>
3rd Sep 2019, 9:57 PM
Gabriele Marra
Gabriele Marra - avatar