- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript code for recursive Fibonacci series
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 ]
Advertisements