Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!