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

156
Visualizações
Difference in output between While and For loop JavaScript - Newbee

It's a basic question; I can't seem to understand why in the code below the while loop output begins with 2 "#" and the for loop start with 1

Console Log Screenshot


let brick = "#";
while (brick.length < 8){

 brick += "#";
  console.log(brick);
}
console.log("For Loop");
for (let i = "#"; i.length <8; i+="#"){
 console.log(i) 
}

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

0

Because in the while loop, you are incrementing before and in the for loop after writing to the console.

Move your brick += "#"; to the end of the while loop and they will behave both the same way:

let brick = "#";

while (brick.length < 8) {
    console.log(brick);
    brick += "#";
}

For-Loop:

for (let i = "#"; i.length < 8; i += "#")
                                  ^ happens AFTER each iteration
about 4 years ago · Juan Pablo Isaza Relatório

0

You have already instatiated the brick at the start. But, when you are looping in the for loop the length is increased after the loop is finished. And the opposite is happening in the while 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