javascript – Why doesn't this loop correctly update this array?

Question:

I try to make a loop that adds to the array fibSeq = [0,1] the sum of the two previous numbers.

That is, the result with 6 iterations should be this: fibSeq = [0,1,1,2,3,5,8,13]

However mine does not update:

function fib(num){
	var fibSeq = [0,1];
	var elultimo = fibSeq.length -1
	var elanterior = elultimo - 1
	var suma = elultimo + elanterior
	
	for (var i = 0; i < num; i++){
		fibSeq.push(suma)
			}
	return fibSeq
}

fib(6)

And returns fibSeq = [0,1,1,1,1,1,1]

I have tried to include the declarations inside the loop

 function fib(num){ var fibSeq = [0,1]; var elultimo = fibSeq.length -1 var elanterior = elultimo - 1 var suma = elultimo + elanterior for (var i = 0; i < num; i++){ elultimo = fibSeq.length -1 elanterior = elultimo - 1 suma = elultimo + elanterior fibSeq.push(suma) } return fibSeq } fib(6)

But then it gives me some weird numbers, not the ones I want (the ones I want are the fibonacci numbers): [0, 1, 1, 3, 5, 7, 9, 11]

I would appreciate an explanation of why the loop doesn't update instead of a solution of how to get the fibonacci numbers since I'm doing this to learn JS and I try to avoid complete solutions because otherwise I don't learn. Thank you.

Answer:

The problem is in the first lines:

var elultimo = fibSeq.length -1
var elanterior = elultimo - 1

Because the value 0 and the value 1 are taken and they are pushed as many times as num , since it is done outside the loop, in addition to the fact that you have the value of the length , not the value that occupies that position in the loop.

The most direct solution and without much modification of the original code is, precisely, to access the values ​​of the array and add them:

function fib(num){
	var fibSeq = [0,1];
	for (var i = 0; i < num; i++){
    var length = fibSeq.length;
    var last = fibSeq[length-1];
    var prevLast = fibSeq[length-2];
    var suma = last + prevLast;
		fibSeq.push(suma)
	}
	return fibSeq
}

console.log(fib(6));

A certain improvement that I propose is to use the syntax of the latest version of Javascript, ES6:

function fib(num){
	let fibSeq = [0,1];
	for (let i = 0; i < num; i++){
    const length = fibSeq.length,
          last = fibSeq[length-1],
          prevLast = fibSeq[length-2],
          suma = last + prevLast;
		fibSeq.push(suma)
	}
	return fibSeq
}

console.log(fib(6));
Scroll to Top