Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

261
Vistas
How do i use while loop while figuring out Fibonacci series?

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);

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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));

about 4 years ago · Juan Pablo Isaza Denunciar

0

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:

  1. It is outside of the function, so repeated runs will cause k to be continuously increased
  2. k is used to track number of iterations, while your code indicates that n should be the quantity of numbers returned

Here is a way more simplified logic, assuming that n is supposed to the number of Fibonacci numbers to be returned:

  1. If n === 1 or n === 2, you return the seed array
  2. Otherwise you simply run a while loop that will only stop running once the seed array exceeds n. 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));

about 4 years ago · Juan Pablo Isaza Denunciar

0

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));

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda