Languages
[Edit]
EN

JavaScript - Fibonacci sequence (iterative algorithm)

13 points
Created by:
Root-ssh
177980

In this short article, we would like to show how to implement Fibonacci sequence using iterative algorithm in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

function fibonacci(number) {
  	if(number < 1) {
    	return NaN;
    }
    var a = 0;
    var b = 1;
    for (var i = 1; i < number; ++i) {
		var c = a + b;
      	a = b;
      	b = c;
    }
    return b;
}


// Usage example:

console.log(fibonacci(1));  // 1
console.log(fibonacci(2));  // 1
console.log(fibonacci(3));  // 2
console.log(fibonacci(4));  // 3
console.log(fibonacci(5));  // 5

 

Alternative titles

  1. JavaScript - Fibonacci number (iterative algorithm)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - math (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join