Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda