w3resource
w3resource logo

JavaScript: Get the first n Fibonacci numbers

(追記) (追記ここまで)
(追記) (追記ここまで)

JavaScript Function: Exercise-6 with Solution

Fibonacci Sequence

Write a JavaScript program to get the first n Fibonacci numbers.

Note: The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . Each subsequent number is the sum of the previous two.

Visual Presentation:

JavaScript: Get the first n Fibonacci numbers

Sample Solution:

JavaScript Code:

// Recursive JavaScript function to generate a Fibonacci series up to the nth term.
var fibonacci_series = function (n) {
 // Base case: if n is less than or equal to 1, return the base series [0, 1].
 if (n <= 1) { return [0, 1]; } else { // Recursive case: generate the Fibonacci series up to (n - 1). var s = fibonacci_series(n - 1); // Calculate the next term in the series and push it to the array. s.push(s[s.length - 1] + s[s.length - 2]); // Return the updated Fibonacci series up to the specified length. return s.slice(0, n); } }; // Example usage: Calculate and print the Fibonacci series up to the 8th term. console.log(fibonacci_series(8)); 

Output:

[0,1,1,2,3,5,8,13]

Flowchart:

Flowchart: JavaScript recursion function- Get the first n Fibonacci numbers

Live Demo:

See the Pen JavaScript - exercises- 6 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that returns the first n Fibonacci numbers using recursion with memoization.
  • Write a JavaScript function that generates the Fibonacci sequence recursively and handles cases where n is less than 1.
  • Write a JavaScript function that computes the Fibonacci sequence recursively and returns an array of the sequence.
  • Write a JavaScript function that uses recursion to generate Fibonacci numbers while storing previously computed values for efficiency.

Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript program to compute the exponent of a number.
Next: Write a JavaScript program to check whether a number is even or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

(追記) (追記ここまで)


(追記) (追記ここまで)
(追記) (追記ここまで)


AltStyle によって変換されたページ (->オリジナル) /