I have just started with Js, I was facing an issue with Js, and could not find a similar solution, would be grateful if anyone helps.
var i = 0;
var j = 1;
var k = 0;
function fibbo(n) {
if (n === 1) {
console.log([0]);
} else if (n === 2) {
console.log([0, 1]);
} else {
while (k <= n) {
var l = [0, 1];
var b = l.length;
l.push(l[b - 2] + l[b - 1]);
k++;
}
}
return l;
}
fibbo(4);
console.log(l);
Make sure to declare variables locally inside the function, if that is where they are used. You can deal with the base cases differently (setting the length
property), and there is the recent JS method Array#at
... :
function fibo(n) {
const l = [0, 1];
while (l.length < n) l.push(l.at(-2) + l.at(-1));
l.length = n; // for the case n < 2
return l;
}
console.log(fibo(4));
Besides attempting to access l
outside of the function, your l
in the return statement is sometimes undefined when 0 or 1 is provided to the function. More importantly, l
shouldn't be defined in the while loop but outside of it.
Moreover, you have variables such as i
and j
that are unused, and k
which is being used but its scope is problematic:
k
to be continuously increasedk
is used to track number of iterations, while your code indicates that n
should be the quantity of numbers returnedHere is a way more simplified logic, assuming that n
is supposed to the number of Fibonacci numbers to be returned:
n === 1
or n === 2
, you return the seed arrayn
. In the while loop, we retain the logic of pushing numbers, but otherwise there is no need to have any other variables being incremented.See proof-of-concept example:
function fibbo(n) {
if (n === 1) {
return [0];
} else if (n === 2) {
return [0, 1];
} else {
const l = [0, 1];
while (n > l.length) {
const b = l.length;
l.push(l[b - 2] + l[b - 1]);
}
return l;
}
}
console.log(fibbo(4));
Using a while
loop, my take will be as follows:
n = 0 || n = 1
. If n > 1
, it loops n - 1
times and within each iteration it adds the sum of previous two values in the existing sequence to the last index.
Once the loop finishes the whole sequence gets trimmed to the length of n
and returned. (This last trimming piece was originally missing in my solution and added after reading trincot's answer)
const fibbo = (n) => {
const sequence = [0, 1];
let i = 2;
let next;
while(i <= n) {
next = sequence[i - 2] + sequence[i - 1];
sequence[i++] = next;
}
return sequence;
}
console.log(fibbo(6));