48
var x = 0;
var y = 1;
var z;

fib[0] = 0;
fib[1] = 1;

for (i = 2; i <= 10; i++) {
  alert(x + y);
  fib[i] = x + y;
  x = y;
  z = y;
}

I'm trying to get to generate a simple Fibonacci Sequence but there no output.

Can anybody let me know what's wrong?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
methuselah
  • 12,766
  • 47
  • 165
  • 315

52 Answers52

88

You have never declared fib to be an array. Use var fib = []; to solve this.

Also, you're never modifying the y variable, neither using it.

The code below makes more sense, plus, it doesn't create unused variables:

var i;
var fib = [0, 1]; // Initialize array!

for (i = 2; i <= 10; i++) {
  // Next fibonacci number = previous + one before previous
  // Translated to JavaScript:
  fib[i] = fib[i - 2] + fib[i - 1];
  console.log(fib[i]);
}
Eliaz Bobadilla
  • 479
  • 4
  • 16
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 8
    Don't forget to output the initial 0 and 1, the first two numbers in the Fibonacci sequence. – tronman Apr 12 '16 at 13:35
  • 2
    I would improve it like so: var sequence = [0,1]; for(var i = 0; i < 10-2; i++){ sequence.push(sequence[i]+sequence[i+1]); } console.log(sequence); – obinoob Jun 22 '17 at 11:51
76

According to the Interview Cake question, the sequence goes 0,1,1,2,3,5,8,13,21. If this is the case, this solution works and is recursive without the use of arrays.

function fibonacci(n) {
   return n < 1 ? 0
        : n <= 2 ? 1
        : fibonacci(n - 1) + fibonacci(n - 2)
}

console.log(fibonacci(4))

Think of it like this.

   fibonacci(4)   .--------> 2 + 1 = 3
      |          /               |
      '--> fibonacci(3) + fibonacci(2)
            |    ^           
            |    '----------- 2 = 1 + 1 <----------.
1st step -> |                     ^                |
            |                     |                |
            '---->  fibonacci(2) -' + fibonacci(1)-'

Take note, this solution is not very efficient though.

Alex Cory
  • 10,635
  • 10
  • 52
  • 62
  • 2
    Although this doesn't scale – Zach Smith Jul 05 '16 at 05:49
  • 14
    this ascii art is the best example i have ever seen of the logic of this +1 – Deprecated Darren Sep 24 '16 at 03:41
  • Best example so far... loved because of the recursive use! – obinoob Jun 22 '17 at 11:49
  • 2
    However expensive, try to process first 500 values! – obinoob Jun 22 '17 at 15:26
  • This is not an answer to question "what's wrong with my code?". This is just some other code with no explanation. It's also one of the worst possible implementations (using recursion). – melpomene Jul 07 '17 at 20:24
  • @melpomene Obviously you didn't read the "think of it like this" portion. Also to your point of "this is not an answer," seems like more people disagree with you because of all the other comments praising the answer. And, if this isn't an answer, why is everyone else providing code and why haven't you commented on other posts...? I will however agree that recursion is not the best solution for this although it is very brief. – Alex Cory Jul 10 '17 at 21:54
  • @AlexCory. Thanks - though I still cannot get why when we have first iteration with `fibonacci(3) + fibonacci(2)`, it does not resolve into `fibonacci(5)`, but keep cycling into `fibonacci(2) + fibonacci(1)` .... – AlexShevyakov Feb 25 '18 at 12:04
  • Have O(2 ^ n), very bad. Better to use some memoized implementation. – Pavan Bahuguni Mar 03 '18 at 01:30
  • Nothing wrong with showing alternate code. Also, recursion is an important concept -- in any Computer algorithms programming course, the Fibonacci sequence is one of the first demonstration of a recursive algorithm. @AlexCory: it is not recursion that makes it bad. It is the fact that the recursion grows exponentially. For example fibonacci(45) or higher will crash your browser. – Vijay Jagdale May 10 '18 at 14:32
  • Please allow me to add a random comment roughly 10 years after the original question and 6 years after this answer. First of all thank you for your answer. This solution is very elegant and readable and does use recursion. However, once you start getting into the higher numbers, even the 20s (e.g. f(20)) performance starts to degrade. At around n > ~48 it starts to lock the browser. This happens with every solution that includes a ternary with recursion not just this one. I haven't had time to discover why that happens but I wanted everyone to be aware of this issue. Thank you again. – codebeard Jul 26 '21 at 08:32
26

Yet another answer would be to use es6 generator functions.

function* fib() {
  var current = a = b = 1;

  yield 1;

  while (true) {
    current = b;

    yield current;

    b = a + b;
    a = current;
  }
}

sequence = fib();
sequence.next(); // 1
sequence.next(); // 1
sequence.next(); // 2
// ...
Dimitris Zorbas
  • 5,187
  • 3
  • 27
  • 33
23

Here's a simple function to iterate the Fibonacci sequence into an array using arguments in the for function more than the body of the loop:

fib = function(numMax){
    for(var fibArray = [0,1], i=0,j=1,k=0; k<numMax;i=j,j=x,k++ ){
        x=i+j;
        fibArray.push(x);
    }
    console.log(fibArray);
}

fib(10)

[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]

irth
  • 1,696
  • 2
  • 15
  • 24
20

You should've declared the fib variable to be an array in the first place (such as var fib = [] or var fib = new Array()) and I think you're a bit confused about the algorithm.
If you use an array to store the fibonacci sequence, you do not need the other auxiliar variables (x,y,z) :

var fib = [0, 1];
for(var i=fib.length; i<10; i++) {
    fib[i] = fib[i-2] + fib[i-1];
}
console.log(fib); 

Click for the demo

You should consider the recursive method too (note that this is an optimised version) :

function fib(n, undefined){
    if(fib.cache[n] === undefined){
        fib.cache[n] = fib(n-1) + fib(n-2);
    }

    return fib.cache[n];
}
fib.cache = [0, 1, 1];

and then, after you call the fibonacci function, you have all the sequence in the fib.cache field :

fib(1000);
console.log(fib.cache);
yivi
  • 42,438
  • 18
  • 116
  • 138
gion_13
  • 41,171
  • 10
  • 96
  • 108
17

The golden ration "phi" ^ n / sqrt(5) is asymptotic to the fibonacci of n, if we round that value up, we indeed get the fibonacci value.

function fib(n) {
    let phi = (1 + Math.sqrt(5))/2;
    let asymp = Math.pow(phi, n) / Math.sqrt(5);

    return Math.round(asymp);
}

fib(1000); // 4.346655768693734e+208 in just a few milliseconds

This runs faster on large numbers compared to the recursion based solutions.

Biereagu Sochima
  • 510
  • 6
  • 13
  • Cool :) For efficiency, I would precompute `Math.sqrt(5)`and `phi` outside the function. For reference, I tested it up to fib(7) and works perfectly. Usage note: fib(0) = 0 – Akseli Palén May 14 '17 at 20:33
  • Yeah, pre-computing phi outside the function would make it faster, i just did this for demonstration. – Biereagu Sochima May 17 '17 at 05:18
  • This is most efficient way to calculate fibonacci value, but it works correctly for not big values. For example it gives wrong value for fib(77). It gives 5527939700884755, but in fact it must be 5527939700884757. – WebBrother Oct 31 '18 at 12:38
  • *same solution* was posted here **years** before this one apparently – vsync Oct 23 '20 at 13:29
10

You're not assigning a value to z, so what do you expect y=z; to do? Likewise you're never actually reading from the array. It looks like you're trying a combination of two different approaches here... try getting rid of the array entirely, and just use:

// Initialization of x and y as before

for (i = 2; i <= 10; i++)
{
    alert(x + y);
    z = x + y;
    x = y;
    y = z;
}

EDIT: The OP changed the code after I'd added this answer. Originally the last line of the loop was y = z; - and that makes sense if you've initialized z as per my code.

If the array is required later, then obviously that needs to be populated still - but otherwise, the code I've given should be fine.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • voting down, since user never asumed y=z expression. To the array, I believe user wanted to use it later – Marian Bazalik Oct 30 '11 at 12:18
  • 4
    @MarianBazalik: Look at the question *before* the edit... it's not my fault the OP fixed the code after I'd pointed out a problem :) – Jon Skeet Oct 30 '11 at 12:20
8

Another easy way to achieve this:

function fibonacciGenerator(n) {
  // declare the array starting with the first 2 values of the fibonacci sequence
  // starting at array index 1, and push current index + previous index to the array
  for (var fibonacci = [0, 1], i = 2; i < n; i++) 
fibonacci.push(fibonacci[i-1] + fibonacci[i - 2])

  return fibonacci
}

console.log(  fibonacciGenerator(10)  )
Mezzanine
  • 91
  • 1
  • 5
  • Was there a genuine problem with my code? I was down voted along with several other people, despite simply responding with an alternate solution. If there is a reason for the down vote, I'd like to see a post to go along with it as it would serve as an opportunity to improve the answer if there is a problem with it. – Mezzanine Jan 27 '18 at 02:27
  • love this solution! I think it's the cleanest so far – vsync Oct 23 '20 at 13:45
  • 1
    love this solution! I think it's the cleanest so far. only issue is with `listFibonacci(0)` & `listFibonacci(1)` – vsync Oct 24 '20 at 07:25
5
function fib(n) {
  if (n <= 1) {
    return n;
  } else {
    return fib(n - 1) + fib(n - 2);
  }
}

fib(10); // returns 55
Benny Code
  • 51,456
  • 28
  • 233
  • 198
Mikhail
  • 11,067
  • 7
  • 28
  • 53
  • 2
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – Blue Jul 15 '16 at 11:43
  • This is not an answer to question "what's wrong with my code?". This is just some other code with no explanation. It's also one of the worst possible implementations (using recursion). – melpomene Jul 07 '17 at 20:21
5

fibonacci 1,000 ... 10,000 ... 100,000

Some answers run into issues when trying to calculate large fibonacci numbers. Others are approximating numbers using phi. This answer will show you how to calculate a precise series of large fibonacci numbers without running into limitations set by JavaScript's floating point implementation.

Below, we generate the first 1,000 fibonacci numbers in a few milliseconds. Later, we'll do 100,000!

const { fromInt, toString, add } =
  Bignum

const bigfib = function* (n = 0)
{
  let a = fromInt (0)
  let b = fromInt (1)
  let _
  while (n >= 0) {
    yield toString (a)
    _ = a
    a = b
    b = add (b, _)
    n = n - 1
  }
}

console.time ('bigfib')
const seq = Array.from (bigfib (1000))
console.timeEnd ('bigfib')
// 25 ms

console.log (seq.length)
// 1001

console.log (seq)
// [ 0, 1, 1, 2, 3, ... 995 more elements ]

Let's see the 1,000th fibonacci number

console.log (seq [1000])
// 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875

10,000

This solution scales quite nicely. We can calculate the first 10,000 fibonacci numbers in under 2 seconds. At this point in the sequence, the numbers are over 2,000 digits long – way beyond the capacity of JavaScript's floating point numbers. Still, our result includes precise values without making approximations.

console.time ('bigfib')
const seq = Array.from (bigfib (10000))
console.timeEnd ('bigfib')
// 1877 ms

console.log (seq.length)
// 10001

console.log (seq [10000] .length)
// 2090

console.log (seq [10000])
// 3364476487 ... 2070 more digits ... 9947366875

Of course all of that magic takes place in Bignum, which we will share now. To get an intuition for how we will design Bignum, recall how you added big numbers using pen and paper as a child...

  1259601512351095520986368
+   50695640938240596831104
---------------------------
                          ?

You add each column, right to left, and when a column overflows into the double digits, remembering to carry the 1 over to the next column...

                 ... <-001
  1259601512351095520986368
+   50695640938240596831104
---------------------------
                  ... <-472

Above, we can see that if we had two 10-digit numbers, it would take approximately 30 simple additions (3 per column) to compute the answer. This is how we will design Bignum to work

const Bignum =
  { fromInt: (n = 0) =>
      n < 10
        ? [ n ]
        : [ n % 10, ...Bignum.fromInt (n / 10 >> 0) ]
        
  , fromString: (s = "0") =>
      Array.from (s, Number) .reverse ()
      
  , toString: (b) =>
      Array.from (b) .reverse () .join ('')
      
  , add: (b1, b2) =>
    {
      const len = Math.max (b1.length, b2.length)
      let answer = []
      let carry = 0
      for (let i = 0; i < len; i = i + 1) {
        const x = b1[i] || 0
        const y = b2[i] || 0
        const sum = x + y + carry
        answer.push (sum % 10)
        carry = sum / 10 >> 0
      }
      if (carry > 0) answer.push (carry)
      return answer
    }
  }

We'll run a quick test to verify our example above

const x =
  fromString ('1259601512351095520986368')

const y =
  fromString ('50695640938240596831104')

console.log (toString (add (x,y)))
// 1310297153289336117817472

And now a complete program demonstration. Expand it to calculate the precise 10,000th fibonacci number in your own browser! Note, the result is the same as the answer provided by wolfram alpha

const Bignum =
  { fromInt: (n = 0) =>
      n < 10
        ? [ n ]
        : [ n % 10, ...Bignum.fromInt (n / 10 >> 0) ]
        
  , fromString: (s = "0") =>
      Array.from (s, Number) .reverse ()
      
  , toString: (b) =>
      Array.from (b) .reverse () .join ('')
      
  , add: (b1, b2) =>
    {
      const len = Math.max (b1.length, b2.length)
      let answer = []
      let carry = 0
      for (let i = 0; i < len; i = i + 1) {
        const x = b1[i] || 0
        const y = b2[i] || 0
        const sum = x + y + carry
        answer.push (sum % 10)
        carry = sum / 10 >> 0
      }
      if (carry > 0) answer.push (carry)
      return answer
    }
  }
  
const { fromInt, toString, add } =
  Bignum

const bigfib = function* (n = 0)
{
  let a = fromInt (0)
  let b = fromInt (1)
  let _
  while (n >= 0) {
    yield toString (a)
    _ = a
    a = b
    b = add (b, _)
    n = n - 1
  }
}

console.time ('bigfib')
const seq = Array.from (bigfib (10000))
console.timeEnd ('bigfib')
// 1877 ms
   
console.log (seq.length)
// 10001

console.log (seq [10000] .length)
// 2090

console.log (seq [10000])
// 3364476487 ... 2070 more digits ... 9947366875

100,000

I was just curious how far this little script could go. It seems like the only limitation is just time and memory. Below, we calculate the first 100,000 fibonacci numbers without approximation. Numbers at this point in the sequence are over 20,000 digits long, wow! It takes 3.18 minutes to complete but the result still matches the answer from wolfram alpha

console.time ('bigfib')
const seq = Array.from (bigfib (100000))
console.timeEnd ('bigfib')
// 191078 ms

console.log (seq .length)
// 100001

console.log (seq [100000] .length)
// 20899

console.log (seq [100000])
// 2597406934 ... 20879 more digits ... 3428746875

BigInt

JavaScript now has native support for BigInt. This allows for calculating huge integers very quickly -

function* fib (n)
{ let a = 0n
  let b = 1n
  let _
  while (n >= 0) {
    yield a.toString()
    _ = a
    a = b
    b = b + _
    n = n - 1
  }
}

console.time("fib(1000)")
const result = Array.from(fib(1000))
console.timeEnd("fib(1000)")
document.body.textContent = JSON.stringify(result, null, 2)
body {
    font-family: monospace;
    white-space: pre;
}
Mulan
  • 129,518
  • 31
  • 228
  • 259
4

I like the fact that there are so many ways to create a fibonacci sequence in JS. I will try to reproduce a few of them. The goal is to output a sequence to console (like {n: 6, fiboNum: 8})

Good ol' closure

// The IIFE form is purposefully omitted. See below.

const fiboGenClosure = () => {
  let [a, b] = [0, 1];
  let n = 0;
  return (fiboNum = a) => {
    [a, b] = [b, a + b];
    return {
      n: n++,
      fiboNum: fiboNum
    };
  };
}

// Gets the sequence until given nth number. Always returns a new copy of the main function, so it is possible to generate multiple independent sequences.

const generateFiboClosure = n => {
  const newSequence = fiboGenClosure();
  for (let i = 0; i <= n; i++) {
    console.log(newSequence());
  }
}

generateFiboClosure(21);

Fancy ES6 generator

Similar to the closure pattern above, using the advantages of generator function and for..of loop.

// The 'n' argument is a substitute for index.

function* fiboGen(n = 0) {
  let [a, b] = [0, 1];
  while (true) {
    yield [a, n++];
    [a, b] = [b, a + b];
  }
}

// Also gives a new sequence every time is invoked.

const generateFibonacci = n => {
  const iterator = fiboGen();
  for (let [value, index] of iterator) {
    console.log({
      n: index,
      fiboNum: value
    });
    if (index >= n) break;
  }
}

generateFibonacci(21);

Tail call recursion

This one is a little tricky, because, now in late 2018, TC optimization is still an issue. But honestly – if you don't use any smart tricks to allow the default JS engine to use a really big numbers, it will get dizzy and claims that the next fibonacci number is "Infinity" by iteration 1477. The stack would probably overflow somewhere around iteration 10 000 (vastly depends on browser, memory etc…). Could be probably padded by try… catch block or check if "Infinity" was reached.

const fibonacciRTC = (n, i = 0, a = 0, b = 1) => {
  console.log({
    n: i,
    fibonacci: a
  });
  if (n === 0) return;
  return fibonacciRTC(--n, ++i, b, a + b);
}

fibonacciRTC(21)

It can be written as a one-liner, if we throe away the console.log thing and simply return a number:

const fibonacciRTC2 = (n, a = 0, b = 1) => n === 0 ? a : fibonacciRTC2(n - 1, b, a + b);

console.log(fibonacciRTC2(21))

Important note!

As I found out reading this mathIsFun article, the fibonacci sequence is valid for negative numbers as well! I tried to implement that in the recursive tail call form above like that:

const fibonacciRTC3 = (n, a = 0, b = 1, sign = n >= 0 ? 1 : -1) => { 
  if (n === 0) return a * sign;
    return fibonacciRTC3(n - sign, b, a + b, sign);
}

console.log(fibonacciRTC3(8)); // 21
console.log(fibonacciRTC3(-8)); // -21
HynekS
  • 2,738
  • 1
  • 19
  • 34
3

A quick way to get ~75

ty @geeves for the catch, I replaced Math.floor for Math.round which seems to get it up to 76 where floating point issues come into play :/ ... either way, I wouldn't want to be using recursion up and until that point.

/**
 * Binet Fibonacci number formula for determining
 * sequence values
 * @param {int} pos - the position in sequence to lookup
 * @returns {int} the Fibonacci value of sequence @pos
 */

var test = [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170,1836311903,2971215073,4807526976,7778742049,12586269025,20365011074,32951280099,53316291173,86267571272,139583862445,225851433717,365435296162,591286729879,956722026041,1548008755920,2504730781961,4052739537881,6557470319842,10610209857723,17167680177565,27777890035288,44945570212853,72723460248141,117669030460994,190392490709135,308061521170129,498454011879264,806515533049393,1304969544928657,2111485077978050,3416454622906707,5527939700884757,8944394323791464,14472334024676221,23416728348467685,37889062373143906,61305790721611591,99194853094755497,160500643816367088,259695496911122585,420196140727489673,679891637638612258,1100087778366101931,1779979416004714189,2880067194370816120,4660046610375530309,7540113804746346429,12200160415121876738,19740274219868223167,31940434634990099905,51680708854858323072,83621143489848422977,135301852344706746049,218922995834555169026];
var fib = function (pos) {
        return Math.round((Math.pow( 1 + Math.sqrt(5), pos) 
            - Math.pow( 1 - Math.sqrt(5), pos)) 
            / (Math.pow(2, pos) * Math.sqrt(5)));
    };

/* This is only for the test */
var max = test.length,
    i = 0,
    frag = document.createDocumentFragment(),
    _div = document.createElement('div'),
    _text = document.createTextNode(''),
    div,
    text,
    err,
    num;
for ( ; i < max; i++) {
    div = _div.cloneNode();
    text = _text.cloneNode();
    num = fib(i);
    if (num !== test[i]) {
        err = i + ' == ' + test[i] + '; got ' + num;
        div.style.color = 'red';
    }
    text.nodeValue = i + ': ' + num;
    div.appendChild(text);
    frag.appendChild(div);
}
document.body.appendChild(frag);
Sparkida
  • 422
  • 4
  • 9
3

There is also a generalization of Binet's formula for negative integers:

static float phi = (1.0f + sqrt(5.0f)) / 2.0f;

int generalized_binet_fib(int n) {
   return round( (pow(phi, n) - cos(n * M_PI) * pow(phi, -n)) / sqrt(5.0f) );
 }

 ...

 for(int i = -10; i < 10; ++i)
    printf("%i ", generalized_binet_fib(i));
galarius
  • 108
  • 9
3

You can get some cache to speedup the algorithm...

var tools = {

    fibonacci : function(n) {
        var cache = {};

        // optional seed cache
        cache[2] = 1;
        cache[3] = 2;
        cache[4] = 3;
        cache[5] = 5;
        cache[6] = 8;

        return execute(n);

        function execute(n) {
            // special cases 0 or 1
            if (n < 2) return n;

            var a = n - 1;
            var b = n - 2;

            if(!cache[a]) cache[a] = execute(a);
            if(!cache[b]) cache[b] = execute(b);

            return cache[a] + cache[b];
        }
    }
};
Samuel Pinto
  • 987
  • 11
  • 8
3

If using ES2015

const fib = (n, prev = 0, current = 1) => n 
  ? fib(--n, current, prev + current) 
  : prev + current

console.log( fib(10) )
vsync
  • 118,978
  • 58
  • 307
  • 400
sqram
  • 7,069
  • 8
  • 48
  • 66
  • 1
    Could easily rewrite as arrow function: `var fib = (n, prev = 0, current = 1) => !n ? prev + current : fib(--n, current, prev+current);` Seems to be showing the n+3 th item and not the nth item. Changing the test to !(n-3) fixes that; however, that means fib(0), fib(1) and fib(2) do not work. – Roger_S Jul 19 '17 at 16:24
  • in order to build accurate set i.e. 0, 1, 1, 2, 3, 5... need to add one more condition ``` function fib(n, prev = 0, current = 1) { if (n > 2) { return fib(--n, current, prev+current); } if (n === 2) { return prev + current; } return n; } ``` – radzserg Aug 31 '20 at 10:44
3

If you need to build a list of fibonacci numbers easily you can use array destructuring assignment to ease your pain:

function fibonacci(n) {
  
  let fibList = [];
  let [a, b] = [0, 1]; // array destructuring to ease your pain

  while (a < n) {
    fibList.push(a);
    [a, b] = [b, a + b]; // less pain, more gain
  }
  
  return fibList;
}

console.log(fibonacci(10)); // prints [0, 1, 1, 2, 3, 5, 8]
dekarpaulvictor
  • 121
  • 1
  • 3
  • I think `while (fibList.length < n)` is what you are looking for (plus some safe checks when n is less than 1). Because your function instead of returning n elements from the fib series, it returns unknown number of elements smaller than n. – ajax333221 May 03 '22 at 05:38
2
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>fibonacci series</title>
        <script type="text/javascript">
                function generateseries(){
                    var fno = document.getElementById("firstno").value;
                    var sno = document.getElementById("secondno").value;
                    var a = parseInt(fno);
                    var result = new Array();
                    result[0] = a;
                    var b = ++fno;
                    var c = b;
                    while (b <= sno) {  
                    result.push(c);
                    document.getElementById("maindiv").innerHTML = "Fibonacci Series between "+fno+ " and " +sno+ " is " +result;
                        c = a + b;
                        a = b;
                        b = c;
                    }
                }
                function numeric(evt){
                    var theEvent = evt || window.event;
                    var key = theEvent.keyCode || theEvent.which;
                    key = String.fromCharCode(key);
                    var regex = /[0-9]|\./;
                    if (!regex.test(key)) {
                        theEvent.returnValue = false;
                        if (theEvent.preventDefault) 
                            theEvent.preventDefault();
                    }
                }

            </script>
        <h1 align="center">Fibonacci Series</h1>
    </head>
    <body>
        <div id="resultdiv" align="center">
        <input type="text" name="firstno" id="firstno" onkeypress="numeric(event)"><br>
        <input type="text" name="secondno" id="secondno" onkeypress="numeric(event)"><br>
        <input type="button" id="result" value="Result" onclick="generateseries();">
        <div id="maindiv"></div>
        </div>
    </body>
</html>
Lukasz Koziara
  • 4,274
  • 5
  • 32
  • 43
AKHIL
  • 135
  • 3
2

I know this is a bit of an old question, but I realized that many of the answers here are utilizing for loops rather than while loops.

Sometimes, while loops are faster than for loops, so I figured I'd contribute some code that runs the Fibonacci sequence in a while loop as well! Use whatever you find suitable to your needs.

function fib(length) {
  var fibArr = [],
    i = 0,
    j = 1;
  fibArr.push(i);
  fibArr.push(j);
  while (fibArr.length <= length) {
    fibArr.push(fibArr[j] + fibArr[i]);
    j++;
    i++;
  }
  return fibArr;
};
fib(15);
  • Nice! However, this actually returns an array of length n+1. If the test in the while loop is changed to (fibArr.length < length), the returned array is of length n. – Roger_S Jul 19 '17 at 16:06
  • "As long as you learn proper and efficient coding patterns Javascript, in today's age, has no loss of performance from its native functions" https://stackoverflow.com/a/29608084/1582030 – Gal Margalit Nov 05 '21 at 14:38
2

sparkida, found an issue with your method. If you check position 10, it returns 54 and causes all subsequent values to be incorrect. You can see this appearing here: http://jsfiddle.net/createanaccount/cdrgyzdz/5/

(function() {
  
function fib(n) {
    var root5 = Math.sqrt(5);
    var val1 = (1 + root5) / 2;
    var val2 = 1 - val1;
    var value = (Math.pow(val1, n) - Math.pow(val2, n)) / root5;

    return Math.floor(value + 0.5);
}
    for (var i = 0; i < 100; i++) {
        document.getElementById("sequence").innerHTML += (0 < i ? ", " : "") + fib(i);
    }

}());
<div id="sequence">
    
</div>
geeves
  • 99
  • 2
  • 4
  • @sparkida - Looking at this a bit more - this method goes completely off the rails starting with the 76th iteration. It gives a value of 3416454622906706. It should be 3416454622906707. Then a few iterations later (81 or 82), the values all are divisible by 100, 1000, etc. – geeves Aug 22 '16 at 14:12
2

Here are examples how to write fibonacci using recursion, generator and reduce.

'use strict'

//------------- using recursion ------------
function fibonacciRecursion(n) {
  return (n < 2) ? n : fibonacciRecursion(n - 2) + fibonacciRecursion(n - 1)
}

// usage
for (let i = 0; i < 10; i++) {
  console.log(fibonacciRecursion(i))
}


//-------------- using generator -----------------
function* fibonacciGenerator() {
  let a = 1,
    b = 0
  while (true) {
    yield b;
    [a, b] = [b, a + b]
  }
}

// usage
const gen = fibonacciGenerator()
for (let i = 0; i < 10; i++) {
  console.log(gen.next().value)
}

//------------- using reduce ---------------------
function fibonacciReduce(n) {
  return new Array(n).fill(0)
    .reduce((prev, curr) => ([prev[0], prev[1]] = [prev[1], prev[0] + prev[1]], prev), [0, 1])[0]
}

// usage
for (let i = 0; i < 10; i++) {
  console.log(fibonacciReduce(i))
}
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
2

I just would like to contribute with a tail call optimized version by ES6. It's quite simple;

var fibonacci = (n, f = 0, s = 1) => n === 0 ? f : fibonacci(--n, s, f + s);
console.log(fibonacci(12));
Redu
  • 25,060
  • 6
  • 56
  • 76
2

There is no need for slow loops, generators or recursive functions (with or without caching). Here is a fast one-liner using Array and reduce.

ECMAScript 6:

var fibonacci=(n)=>Array(n).fill().reduce((a,b,c)=>a.concat(c<2?c:a[c-1]+a[c-2]),[])

ECMAScript 5:

function fibonacci(n){
    return Array.apply(null,{length:n}).reduce(function(a,b,c){return a.concat((c<2)?c:a[c-1]+a[c-2]);},[]);
}

Tested in Chrome 59 (Windows 10):

fibonacci(10); // 0 ms -> (10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

JavaScript can handle numbers up to 1476 before reaching Infinity.

fibonacci(1476); // 11ms -> (1476) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...]
evoldoc
  • 31
  • 2
2

Another implementation, while recursive is very fast and uses single inline function. It hits the javascript 64-bit number precision limit, starting 80th sequence (as do all other algorithms): For example if you want the 78th term (78 goes in the last parenthesis):

(function (n,i,p,r){p=(p||0)+r||1;i=i?i+1:1;return i<=n?arguments.callee(n,i,r,p):r}(78));

will return: 8944394323791464

This is backwards compatible all the way to ECMASCRIPT4 - I tested it with IE7 and it works!

Vijay Jagdale
  • 2,321
  • 2
  • 18
  • 16
  • [this answer](https://stackoverflow.com/a/50376273/633183) shows how to compute term 100,000 and beyond – Mulan Sep 28 '18 at 17:22
1

This script will take a number as parameter, that you want your Fibonacci sequence to go.

function calculateFib(num) {
    var fibArray = [];
    var counter = 0;

    if (fibArray.length == 0) {
        fibArray.push(
            counter
        );
        counter++
    };

    fibArray.push(fibArray[fibArray.length - 1] + counter);

    do {
        var lastIndex = fibArray[fibArray.length - 1];
        var snLastIndex = fibArray[fibArray.length - 2];
        if (lastIndex + snLastIndex < num) {
            fibArray.push(lastIndex + snLastIndex);
        }

    } while (lastIndex + snLastIndex < num);

    return fibArray;

};
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Sehul Viras
  • 587
  • 5
  • 9
1

This is what I came up with

//fibonacci numbers
//0,1,1,2,3,5,8,13,21,34,55,89
//print out the first ten fibonacci numbers
'use strict';
function printFobonacciNumbers(n) {
    var firstNumber = 0,
        secondNumber = 1,        
        fibNumbers = [];
    if (n <= 0) {
        return fibNumbers;
    }
    if (n === 1) {
        return fibNumbers.push(firstNumber);
    }
    //if we are here,we should have at least two numbers in the array
    fibNumbers[0] = firstNumber;
    fibNumbers[1] = secondNumber;
    for (var i = 2; i <= n; i++) {
        fibNumbers[i] = fibNumbers[(i - 1)] + fibNumbers[(i - 2)];
    }
    return fibNumbers;
}

var result = printFobonacciNumbers(10);
if (result) {
    for (var i = 0; i < result.length; i++) {
        console.log(result[i]);
    }
}
dotnetdev_2009
  • 722
  • 1
  • 11
  • 28
1

Beginner, not too elegant, but shows the basic steps and deductions in JavaScript

/* Array Four Million Numbers */
var j = [];
var x = [1,2];
var even = [];
for (var i = 1;i<4000001;i++){
   j.push(i);
    }
// Array Even Million
i = 1;
while (i<4000001){
    var k = j[i] + j[i-1];
    j[i + 1]  = k;
    if (k < 4000001){
        x.push(k);
        }
    i++;
    }
var total = 0;
for (w in x){
    if (x[w] %2 === 0){
        even.push(x[w]);
        }
 }
for (num in even){
    total += even[num];
 }
console.log(x);
console.log(even);
console.log(total); 
Enogwe Victor
  • 70
  • 1
  • 5
1

Fibonacci (one-liner)

function fibonacci(n) {
  return (n <= 1) ? n : fibonacci(n - 1) + fibonacci(n - 2);
}

Fibonacci (recursive)

function fibonacci(number) {
  // n <= 1
  if (number <= 0) {
    return n;
  } else {
    // f(n) = f(n-1) + f(n-2)
    return fibonacci(number - 1) + fibonacci(number - 2);
  }
};

console.log('f(14) = ' + fibonacci(14)); // 377

Fibonacci (iterative)

 function fibonacci(number) {
  // n < 2
  if (number <= 0) {
    return number ;
  } else {
    var n = 2; // n = 2
    var fn_1 = 0; // f(n-2), if n=2
    var fn_2 = 1; // f(n-1), if n=2   

    // n >= 2
    while (n <= number) {
      var aa = fn_2; // f(n-1)
      var fn = fn_1 + fn_2; // f(n)

      // Preparation for next loop
      fn_1 = aa;
      fn_2 = fn;

      n++;
    }

    return fn_2;
  }
};

console.log('f(14) = ' + fibonacci(14)); // 377

Fibonacci (with Tail Call Optimization)

function fibonacci(number) {
  if (number <= 1) {
    return number;
  }

  function recursion(length, originalLength, previous, next) {
    if (length === originalLength)
      return previous + next;

    return recursion(length + 1, originalLength, next, previous + next);
  }

  return recursion(1, number - 1, 0, 1);
}

console.log(`f(14) = ${fibonacci(14)}`); // 377
Benny Code
  • 51,456
  • 28
  • 233
  • 198
  • 3
    Recursive implementation for Fibonacci has an exponential complexity, this should not be used to compute large Fibonacci number. – yunandtidus Jun 14 '17 at 16:23
1

My 2 cents:

function fibonacci(num) {
  return Array.apply(null, Array(num)).reduce(function(acc, curr, idx) {
    return idx > 2 ? acc.concat(acc[idx-1] + acc[idx-2]) : acc;
  }, [0, 1, 1]);
}

console.log(fibonacci(10));
Jonatas Walker
  • 13,583
  • 5
  • 53
  • 82
1

I would like to add some more code as an answer :), Its never too late to code :P

function fibonacciRecursive(a, b, counter, len) {
    if (counter <= len) {
        console.log(a);
        fibonacciRecursive(b, a + b, counter + 1, len);
    }
}

fibonacciRecursive(0, 1, 1, 20);

Result

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Vikas Bansal
  • 10,662
  • 14
  • 58
  • 100
1
function fibo(count) {

    //when count is 0, just return 
    if (!count) return;

    //Push 0 as the first element into an array
    var fibArr = [0];

    //when count is 1, just print and return
    if (count === 1) {
        console.log(fibArr);
        return;
    }

    //Now push 1 as the next element to the same array
    fibArr.push(1);

    //Start the iteration from 2 to the count
    for(var i = 2, len = count; i < len; i++) {
        //Addition of previous and one before previous
        fibArr.push(fibArr[i-1] + fibArr[i-2]);
    }

    //outputs the final fibonacci series
    console.log(fibArr);
}

Whatever count we need, we can give it to above fibo method and get the fibonacci series upto the count.

fibo(20); //output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
Nithin
  • 19
  • 1
1

I've tried this: it might work:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fibonacci</title>
    <style>
        * {
            outline: 0px;
            margin: 0px;
        }

        input[type="number"] {
            color: blue;
            border: 2px solid black;
            width: 99.58vw;
        }
    </style>
</head>

<body>
    <div id="myDiv" style="color: white;background-color: blue;">Numbers Here</div>
    <input type="number" id="input1" oninput="fibonacciProgram(this.value)" placeholder="Type Some Numbers Here">
    <script>
        function fibonacciProgram(numberCount) {
            let resultElement = document.getElementById("myDiv");
            resultElement.innerHTML = " ";
            if (isNaN(numberCount) || numberCount <= 0) {
                resultElement.innerHTML = "please enter a number";
                return;
            }
            let firstBox = 0;
            let secondBox = 1;
            let swichBox;
            let entries = [];
            entries.push(secondBox);
            while (numberCount > 1) {
                swichBox = firstBox + secondBox;
                entries.push(swichBox);
                firstBox = secondBox;
                secondBox = swichBox;
                numberCount--;
            }
            resultElement.innerHTML = entries.join(', ');
        }
    </script>
</body>

</html>
Green
  • 486
  • 2
  • 11
  • 31
1
    // using recursive approach and in one line
    const fib = x => (x <= 1)? x : fib (x - 1) + fib(x -2);
    fib(15); // 610

    // display the 15 first 
    Array.from({ length: 15 }, (v, i) => fib(i)); 
    // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
    
    

    // using memoization approach
    function fibonacci(num, memo) {
      memo = memo || {};
      if (memo[num]) return memo[num];
      if (num === 0) return 0;
      if (num === 1) return 1;
      return memo[num] = fibonacci(num - 1, memo) + fibonacci(num - 2, memo);
    }
    fibonacci(15); // 610

    // display the 15 first 
    Array.from({ length: 15 }, (v, i) => fibonacci(i));
    // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Leo Lanese
  • 476
  • 4
  • 5
0

You Could Try This Fibonacci Solution Here

var a = 0;
console.log(a);
var b = 1;
console.log(b);
var c;
for (i = 0; i < 3; i++) {
  c = a + b;
  console.log(c);
  a = b + c;
  console.log(a);
  b = c + a;
  console.log(b);
}
m4n0
  • 29,823
  • 27
  • 76
  • 89
0

Here is a function that displays a generated Fibonacci sequence in full while using recursion:

function fibonacci (n, length) {
    if (n < 2) {
        return [1];   
    }
    if (n < 3) {
        return [1, 1];
    }

    let a = fibonacci(n - 1);
    a.push(a[n - 2] + a[n - 3]);
    return (a.length === length) 
            ? a.map(val => console.log(val)) 
            : a;

};

The output for fibonacci(5, 5) will be:

1
1
2
3
5

The value that is assigned to a is the returned value of the fibonacci function. On the following line, the next value of the fibonacci sequence is calculated and pushed to the end of the a array.

The length parameter of the fibonacci function is used to compare the length of the sequence that is the a array and must be the same as n parameter. When the length of the sequence matches the length parameter, the a array is outputted to the console, otherwise the function returns the a array and repeats.

0

es6 - Symbol.iterator and generator functions:

let fibonacci = {
    *[Symbol.iterator]() {
        let pre = 0, cur = 1
        for (;;) {
            [ pre, cur ] = [ cur, pre + cur ]
            yield cur
        }
    }
}

for (let n of fibonacci) {
    if (n > 1000)
        break
    console.log(n)
}
Aran Dekar
  • 461
  • 5
  • 12
0

I got asked this question recently, and this was my solution:

function fib(n) {
  const arr = [0,1]; // the inital array, we need something to sum at the very beginning
  for (let i = 2; i <= n; i++) { // we want the last number, so don't forget the '=' sign
    let a = arr[i-1]; // previous Number
    let b = arr[i-2]; // the one before that
    arr.push(a+b); // push the result
  }
  return arr; // if you want the n-th number, just return arr[n] or arr.length - 1
}

console.log(fib(4));

A recursive solution would be:

// NOTE: This has extremly bad performance => Exponential time complexity 2^n

function fib(n) {
  if (n < 2) {
    return n;
  }
  return fib(n-1) + fib(n-2);
}

console.log('The n-th fibonacci number: ', fib(6));
console.log('The entire fibonacci sequence: ');

// Let's see the entire fibonacci sequence
for (let i = 0; i <= 6; i++) {
   console.log(fib(i));
}

Like mentioned earlier, the above recursive solution has a very bad impact on performance. Fortunately, there's a solution and it's called memoization:

// LET'S CREATE A MEMO FUNCTION 
// (and use it on the recursive **fib** function from above):

// We want to pass in a function which is going to, eventually, 
// use this utility function
function memo(fn) { 
  const cache = {}; 
  // let's make it reusable, and by that I mean, let's assume that
  // we don't know the number of arguments that will be eventually passed in 
 return function(...args) {
// if we already call this function with the same args?
// YES => return them
   if(cache[args]) { 
     console.log('cached', args[0]);
     return cache[args];
   }
//    otherwise, we want to call our function 
// (the one using this 'memo' function) and pass in the arguments
// w/ the help of 'apply'
   const res = fn.apply(this, args);
   cache[args] = res; 
   // we want to store the result, so later if we'll be able to
   // return that if the args don't change
   console.log('not cached', args[0]);
   return res; // don't forget to return the result of it :)
 }
}

// Now, let's use the memoized function:
// NOTE: Remember the above function has to change in a way
// that it calls the memoized function instead of itself

function fastFib(n) {
//   SAME LOGIC AS BEFORE
  if (n<2) { 
    return n;
  }
// But, here is where the 'magic' happens
// Very important: We want to call the instantiated 'fibMemo' function 
// and NOT 'fastFib', cause then it wouldn't be so fast, right :)   
  return fibMemo(n-1) + fibMemo(n-2);
}

// DO NOT CALL IT, JUST PASS IT IN
const fibMemo = memo(fastFib); 

// HERE WE WANT TO PASS IN THE ARGUMENT
console.log(fibMemo(6));
Dženis H.
  • 7,284
  • 3
  • 25
  • 44
0

You can refer to below simple recursive function.

function fib(n){
      if (n <= 2) return 1;
      return fib(n-1) + fib(n-2);
 }

console.log(fib(10)) //55 // Pass on any value to get fibonacci of.
Avadhut Thorat
  • 997
  • 11
  • 7
0

To reduce the time and optimize the performance we can make use of memoization in fibo, because fibo(40) will take too much time to calculate the result, to handle such cases memoization comes in picture. [Memoization is basically use to cache the values based on the input, In simple words we can say we store th result of previous values).

function fibo(n, prevValues = []) {
  if (prevValues[n] != null) {
    return prevValues[n];
  }
  let result;
  if (n <= 2) {
    result = 1
  } else {
    result = fibo(n - 1, prevValues) + fibo(n - 2, prevValues);
  }
  prevValues[n] = result;
  return result;
}

console.log(fibo(41))
Ronak07
  • 894
  • 5
  • 26
0
let maxNum = 10; // can change as per your desired length
const fibonnaci = (terms) => {
  let series = [0, 1], a = 1, b = 0, f = 0;
  for (let i = 0; i < terms; b = a, a = f, i++) {
    f = b + a
    series.push(f)
  }
  console.log(series) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …]
}
fibonnaci(maxNum)

cheers !

Sk Sunny
  • 71
  • 6
0
<!DOCTYPE html>
<html>
<body>
<p id="fibonacci">Fibonacci</p>
<script>
var fibo = fibonacci() 
function* fibonacci() {
    var x = 1, y = 1, z = 0
    yield* [x, y];
    while(true) {
        z = x + y, x = y, y = z;
        yield z;
    }
}
setInterval(
    () => document.getElementById("fibonacci").innerHTML = fibo.next().value
, 1000);
</script>
</body>
</html>
Braden Borman
  • 309
  • 1
  • 8
0

A solution I came across a while ago

function fib(n) {
 if(n<0) throw new Error('Incorrect number in a Fibonacci sequence');
 const phi = (1 + Math.sqrt(5)) / 2;
 return Math.round(Math.pow(phi, n) / Math.sqrt(5));
}

Time O(1)

Space O(1)

Reference: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html

A.J
  • 43
  • 1
  • 6
0

Most simple one

var output = [0,1];

for (let i = 2; i < 10; i++) {  

 output.push(output[i-2] + output[i-1])  
 
}
console.log(output)
Shemeer M Ali
  • 1,030
  • 15
  • 39
0

A solution using BigInt to deal with big numbers and lodash memoize to cache results. This improves the performance quite a bit.

const fibBigInt = (n) => {
  if (n <= BigInt(1)) {
    return n
  }
  return fibonacciBigInt(n - BigInt(1)) + fibonacciBigInt(n - BigInt(2))
}
const fibonacciBigInt = _.memoize(fibBigInt)

console.log(fibonacciBigInt(125n))

Output: 59425114757512643212875125n

Source: https://github.com/bertolo1988/my-util-js-functions/blob/main/src/fibonacci/fibonacci.js

Tiago Bértolo
  • 3,874
  • 3
  • 35
  • 53
0

My 2 cents:

function fibonacciGenerator( n = 0 )
  {
  if (n<0) throw 'Fibonacci generator accept only positive value'  
  let arr = [0,1,1];
  if   (n < 2)  arr.splice( n+1, 2-n)
  else          for (let i=2; i<n; ++i)  arr.push( arr[i] + arr[i-1] )
  return arr.join('-')
  }


console.log( '0 ->', fibonacciGenerator(0) )
console.log( '1 ->', fibonacciGenerator(1) )
console.log( '2 ->', fibonacciGenerator(2) )
console.log( '3 ->', fibonacciGenerator(3) )
console.log( '12 ->', fibonacciGenerator(12) )

console.log( '-8 ->' )
console.log( fibonacciGenerator(-8) )
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
-1

Here is another one with proper tail call.

The recursive inner fib function can reuse the stack because everything is needed (the array of numbers) to produce the next number is passed in as an argument, no additional expressions to evaluate.

However tail call optimization introduced in ES2015.

Also one drawback is it gets the array length in every iteration (but only once) to generate the following number and getting the elements of the array upon their index (it is faster though than pop or splice or other array methods) but I did not performance tested the whole solution.

var fibonacci = function(len) {
  var fib = function(seq) {
    var seqLen = seq.length;
    if (seqLen === len) {
      return seq;
    } else {
      var curr = seq[seqLen - 1];
      var prev = seq[seqLen - 2];
      seq[seqLen] = curr + prev;
      return fib(seq);
    }
  }
  return len < 2 ? [0] : fib([0, 1]);
}

console.log(fibonacci(100));
cstuncsik
  • 2,698
  • 2
  • 16
  • 20
-1
(function fib(max,i,j) {
  i = i||this[0];j=j||this[1];
  if (max!==0) {
    this.push(i+j);
    max--;
    return fib.bind(this, max, j, i+j)();
  } else {
    return this;
  }
}.bind([0,1], 10))();

result :[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]

Anja Ishmukhametova
  • 1,535
  • 16
  • 14
-1

You can use recursion and cache the results in a functional way.

const fibonacci = (n, cache = {1: 1, 2: 1}) =>
  cache[n] || (cache[n] = fibonacci(--n, cache) + fibonacci(--n, cache));
  
console.log(fibonacci(1000));
console.log(fibonacci(100));
console.log(fibonacci(10));
Juan
  • 603
  • 7
  • 15
-1

I think this one is simple enough to understand:

function fibonacci(limit) {
    let result = [0, 1];

    for (var i = 2; i < limit; i++) {
        result[result.length] = result[result.length - 1] + result[result.length - 2];
    }

    return result;

}
// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
console.log(fibonacci(10));
Tonni
  • 94
  • 2
  • 7
  • 2
    **From review queue**: May I request you to please add some context around your source-code. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post. – RBT May 21 '17 at 02:50
-1

A better option would be using recursion but the following example can help you to understand logic!

Edit: Correction, recursion will eventually exhaust system out of resources without archiving expected results. The following example it uses simple logic, and it can process very fast...

var sequence = [0,1];
var range = 10;

for(var i = 0; i < range-2; i++){
    sequence.push(sequence[i]+sequence[i+1]);
}

console.log(sequence);
obinoob
  • 677
  • 4
  • 13
  • 34
  • 2
    Recursion is an awful idea for computing fibonacci numbers. – melpomene Jul 07 '17 at 20:21
  • You're totally right about that that's why I've not used it! You can test my solution and I'm sure it will run way faster than any recursion solution. I just mentioned that recursion would be a better solution in order to understand how it works but even that might be bad, so perhaps I need to change description... – obinoob Oct 13 '17 at 09:17
  • melpomene yes I agree! Not sure why I have said that lol, I know that recursion wastes a lot of resources, probably will run out of memory etc... That's why I have wrote it without recursion! – obinoob Nov 09 '17 at 20:14
-1
function getFibonacciNumbers(n) {    
    var sequence = [0, 1];
    if (n === 0 || n === 1) {
        return sequence[n];
    } 
    else {
        for (var i = 2; i < n; i++ ) {
            var sum = sequence[i - 1] + sequence[i - 2];
            sequence.push(sum);
        }
    return sequence;
    }
}
console.log(getFibonacciNumbers(0));
console.log(getFibonacciNumbers(1));
console.log(getFibonacciNumbers(9));
Mary Pieroszkiewicz
  • 363
  • 1
  • 5
  • 11
  • 3
    This is not an answer to question "what's wrong with my code?". This is just some other code with no explanation. – melpomene Jul 07 '17 at 20:20
-1
var a = -1;
var b=0;
var temp =0;
var arry = [];
for(var i=1;i<100;i++){
    temp = a+b;
    a=b;
    b=temp;
    arry.push(b*-1);
}
console.log(arry);
-1

Another solution could be:

const fib = (num) => {
    if(num === 0) return 0;
    const arr=[0,1];
    let counter=2;      
    while(counter <=num){
        arr[counter]=arr[counter -1] + arr[counter -2]
        counter ++
    }
    return arr
}

This function returns an Array of the Fibonacci sequence based on given limit.

fib(5) // returns [0, 1, 1, 2, 3, 5]