while loops · loop 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 berulang
while (test) { ... }berjalan lagi dan lagi, selama tes tetaptrue.- Ia memeriksa tes sebelum setiap putaran — sehingga badannya mungkin berjalan nol kali.
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).
Buat kemajuan setiap putaran
- Sesuatu di dalamnya harus menggerakkan tes menuju
false. - Jika tidak ada perubahan, loop tidak pernah berhenti — loop tak terhingga (tombol Stop menyelamatkan Anda).
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 · Setiap lompatan menggandakan n
while re-checks its test each pass. n must change, or it runs forever. · while memeriksa ulang ujiannya setiap lompatan. n harus berubah, atau ia akan berjalan selamanya.
Common mistakes
- Change the condition inside the loop, or it runs forever.
- A
whilechecks its condition first, so it may run zero times.
Kesalahan umum
- Ubah kondisi di dalam loop, atau ia akan berjalan selamanya.
- A
whilememeriksa kondisinya terlebih dahulu, sehingga mungkin berjalan nol kali.
Now you try
- Use a
whileloop. - Press Check answer to test it.
Sekarang Anda coba
- Gunakan loop
while. - Tekan Cek jawaban untuk mengujinya.
let n = 3. Use a while loop to count down: log 3, 2, 1, one per line. · let n = 3. Gunakan gelung while untuk mengira mundur: catatkan 3, 2, 1, satu per baris.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
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. Selagi n adalah 16 atau kurang, catatkan n kemudian gandakannya. Output sepatutnya ialah 1, 2, 4, 8, 16.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Use a while loop to add up 1 to 4, then log the total (it is 10). · Gunakan loop while untuk menjumlahkan dari 1 hingga 4, lalu log totalnya (yaitu 10).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.