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

85
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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