sagar patel sagar patel - 2 months ago 16
Javascript Question

confused generating fibonacci sequence

(i) When I run below code,

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

Output: 0 1 undefined 1 NaN NaN


(ii) When I run below code,

function generateFib(num) {
var fib = [];
for(var i=1; i <= num; i++) {
if (i === 1) {
fib.push(0);
} else if (i == 2) {
fib.push(1);
} else {
fib.push(fib[i - 2] + fib[i - 3]);
}
}
return fib;
}
generateFib(10);

Output: 0 1 1 2 3 5


I am confused between two code could you please explain me, thank you.

Answer

Follow the loops iterations one by one

in the third iteration,

fib[2] = fib[2-2] + fib[2-3]; is fib[2] = fib[0] + fib[-1];

fib[2] = 0 + undefined;

fib[2] = undefined;

in the fourth iteration,

fib[3] = fib[3-2] + fib[3-3]; is fib[3] = fib[1] + fib[0];

fib[3] = 1 + 0;

in the fifth iteration,

fib[4] = fib[4-2] + fib[4-3]; is fib[4] = fib[2] + fib[1];

fib[4] = undefined + 1;

fib[4] = NaN;

You can figure out the rest.

Btw you could use a debugger with breakpoints.

It would be really useful in this situation.