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

178
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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