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

94
Views
Confusion in loops

If I put 'let tableValue' outside a while loop then it shows the same number 10 times and when I write it inside the while loop then it prints a table of the value 'n'.

What is the difference between these two things?

function table(n) {
  let i = 1;
  let tableValue = (n * i);
  while (i <= 10) {
    console.log(tableValue);
    i++;
  }
}
table(9);

function table(n) {
  let i = 1;
  while (i <= 10) {
    let tableValue = (n * i);
    console.log(tableValue);
    i++;
  }
}
table(9);

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

If you put this line:

let tableValue = (n * i);

outside your loop, as you have in the first example, then tableValue is set once, before the loop begins, and when you log it, you are logging the same value each time, because you never change it after that.

This statement is not a declaration that tableValue is always n * i at all times, even when n and i change. If you want that, you need to recalculate tableValue whenever either of the values changes. That's what you're accomplishing by putting that line inside your loop.

Computers execute code one line at a time and don't look ahead or backward much. When code changes your program's state, such as setting a variable value, that change persists until it is later changed again.

about 4 years ago · Juan Pablo Isaza Report

0

Use:

function table(n) {
  let i = 1;
  let tableValue = (n * i); // This is 1 * 9, because it is outside the while loop ( the while loop block } don’t worry that it's inside the function, it still needs to be in the while block. I think that’s why you're getting confused.
  while (i <= 10) {
     console.log(tableValue);
     i++;
  }
}
table(9);

I’ve put comments on the line in which I think needs explaining.

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!