for loops · loop for
Repeating with a for loop
- A loop runs the same block many times, so you don't repeat yourself.
for (let i = 1; i <= 5; i++) { ... }has three parts: starti = 1, testi <= 5, stepi++.
Mengulang dengan loop for
- Loop menjalankan blok yang sama berkali-kali, sehingga Anda tidak perlu mengulang diri sendiri.
for (let i = 1; i <= 5; i++) { ... }memiliki tiga bagian: mulaii = 1, tesi <= 5, langkahi++.
for (let i = 1; i <= 3; i++) {
console.log(i); // → 1, then 2, then 3
}
Build a running total
- Keep a variable outside the loop and add to it on every pass.
Bangun total berjalan
- Simpan variabel di luar loop dan tambahkan nilainya pada setiap putaran.
let total = 0;
for (let i = 1; i <= 10; i++) {
total = total + i;
}
console.log(total); // → 55
Trace the running total · Jejak total berjalan
A loop repeats its body. Step through the passes and watch total grow. · Loop mengulang isinya. Lanjutkan lompatan dan lihat total bertambah.
Watch out
i <= 5stops after 5;i < 5stops before 5. Picking the wrong one is the classic "off-by-one" bug.- Start the total at
0before the loop, not inside it.
Hati-hati
i <= 5berhenti setelah 5;i < 5berhenti sebelum 5. Memilih yang salah adalah bug "off-by-one" klasik.- Mulai total di
0sebelum loop, bukan di dalamnya.
Common mistakes
for (let i = 0; i < n; i++)runsntimes.- Declare the counter with
let, not without.
Kesalahan umum
for (let i = 0; i < n; i++)berjalannkali.- Deklarasikan penghitung dengan
let, bukan tanpa.
Now you try
- Use a
forloop. - Press Check answer to test it.
Sekarang Anda coba
- Gunakan loop
for. - Tekan Cek jawaban untuk mengujinya.
Use a for loop to log the numbers 1 to 5, one per line. · Gunakan loop for untuk log angka dari 1 hingga 5, satu per baris.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Use a for loop to add up 1 to 10, then log the total (it is 55). · Gunakan loop for untuk menjumlahkan dari 1 hingga 10, lalu log totalnya (yaitu 55).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Use a for loop to log the even numbers 2, 4, 6, one per line (step by 2 with i += 2). · Gunakan loop for untuk log angka genap 2, 4, 6, satu per baris (langkah 2 dengan i += 2).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.