I'm trying to find the nth value of the fib sequence in javascript, but I got stuck with another problem prior to that and I'm trying to understand why.
function nthFib(n) {
var fib = [0, 1];
var l = fib[fib.length-1];
var s = fib[fib.length-2];
while(fib.length < n) {
fib.push(fib[fib.length-1] + fib[fib.length-2]);
}
console.log(fib);
}
nthFib(5);
Right now when I console log I'm getting what I want which is the array building up: [0, 1, 1, 2, 3]
BUT if I do this in the while loop instead to have cleaner code:
while(fib.length < n) {
fib.push(s + l);
}
I guess my while loop doesn't have access to those variables and in turn I get this result: [0, 1, 1, 1, 1]
WHY?
You have to modify
s, l
inside the while loop. Take a look at this code.