while loops · loops while
while repeats
while (test) { ... }runs again and again, as long as the test staystrue.- It checks the test before each pass — so the body might run zero times.
while repete
while (test) { ... }roda repetidamente, enquanto o teste permanecertrue.- Ele verifica o teste antes de cada passagem — então o corpo pode rodar zero vezes.
let n = 1;
while (n <= 3) {
console.log(n); // → 1, then 2, then 3
n++;
}
Make progress every pass
- Something inside must move the test toward
false. - If nothing changes, the loop never stops — an infinite loop (the Stop button saves you).
Faça progresso a cada passagem
- Algo dentro deve mover o teste em direção a
false. - Se nada mudar, o loop nunca para — um loop infinito (o botão Stop salva você).
let n = 1;
while (n < 50) {
n = n * 2; // 2, 4, 8, 16, 32, 64 — then stop
}
console.log(n); // → 64
Each pass doubles n · Cada passagem dobra n
while re-checks its test each pass. n must change, or it runs forever. · while re-verifica seu teste a cada passagem. n deve mudar, ou ele roda para sempre.
Common mistakes
- Change the condition inside the loop, or it runs forever.
- A
whilechecks its condition first, so it may run zero times.
Erros comuns
- Mude a condição dentro do loop, ou ele roda para sempre.
- Um
whileverifica sua condição primeiro, então pode rodar zero vezes.
Now you try
- Use a
whileloop. - Press Check answer to test it.
Agora você tenta
- Use um loop
while. - Pressione Check answer para testá-lo.
let n = 3. Use a while loop to count down · para baixo: log 3, 2, 1, one per line. · let n = 3. Use um loop while para contar para baixo: faça log de 3, 2, 1, um por linha.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
let n = 1. While n is 16 or less, log n then double it. Output should be 1, 2, 4, 8, 16. · let n = 1. Enquanto n for menor ou igual a 16, faça log de n depois dobre-o. A saída deve ser 1, 2, 4, 8, 16.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Use a while loop to add up 1 to · até 4, then log the total (it is 10). · Use um loop while para somar de 1 a 4, depois faça log do total (é 10).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.