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

184
Visualizações
Why does the outcome change when the variable is declared within the while loop?

I have two simple functions here. In the loop function I have defined facky as one at the top of the function. Two things I do not understand:

  1. The answer to console.log(loop(5)) is 120 when facky is defined at the top of loop
  2. When I move var facky = 1; within the while loop, the answer is 2. I understand why this is two. What I don't understand is why the behavior is different when the variable is outside?

function loop(size) {

  while (size > 1) {
    var facky = 1;
    facky = facky * size;
    size = size - 1;

  }
  clunk(facky);
}


function clunk(times) {
  var num = times;

  while (num > 0) {
    console.log("clunk");
    num = num - 1;
  }
}

loop(5);

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In your while loop, whenever the loop iterates, facky is reset to 1, so it will only print twice because the last iteration of the while loop multiplies facky by 2.

When you move the declaration outside of the while loop, facky does not reset after every iteration and takes on the value of 5!, or 120 after the final iteration.

about 4 years ago · Juan Pablo Isaza Relatório

0

You shouldn't declare a variable inside a loop. Try this instead:

function loop(size) {
  
  var facky = 1;

  while (size > 1) {
    facky = facky * size;
    size = size - 1;
  }

  clunk(facky);

}
about 4 years ago · Juan Pablo Isaza Relatório

0

It doesn't really matter where you declare the var facky, it's always function-scoped.

What matters is whether you reset facky = 1 in every iteration of your loop, or whether you only initialise it once before the loop.

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