We have to write a recursive function fibonacci() that takes in a number n and returns an array with first n elements of fibonacci series. Therefore, let’s write the code for this function −
Example
const fibonacci = (n, res = [], count = 1, last = 0) => { if(n){ return fibonacci(n-1, res.concat(count), count+last, count); }; return res; }; console.log(fibonacci(8)); console.log(fibonacci(0)); console.log(fibonacci(1)); console.log(fibonacci(19));
Output
The output in the console will be −
[ 1, 1, 2, 3, 5, 8, 13, 21 ] [] [ 1 ] [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181 ]