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

104
Visualizações
Why is this for loop looping infinitely?
let n = 5;

for (let a = 1, b = Math.pow(2, a); b <= n; a++) {
   console.log(b);
}

I don't understand why b doesn't increase as a increases. Do I have to somehow pass a to b again?

If there's no way to make this loop work this way, can someone tell me how I could rewrite it so it works?

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

Once b is initialized, your code never changes it, so the loop condition is always true.

You could use

let n = 5;

for (b = 2; b <= n; b*=2) {
   console.log(b);
}

about 4 years ago · Santiago Gelvez Relatório

0

You can get it working like below. Your case is more likely fit for while or do while loop.

let n = 5;
let a = 1;
   
while(powToA(a)<=n) {
   console.log(powToA(a));
   a++;
}


function powToA(a) {
  return Math.pow(2, a);
}

about 4 years ago · Santiago Gelvez Relatório

0

b is of value type not of reference type. So updating a will not automatically update value of b

You have to update it manually

for (let a = 1,b =Math.pow(2,a); b <= n; a++,b=Math.pow(2,a)) {
   console.log(a);
}
about 4 years ago · Santiago Gelvez 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