for Loop
The for
loop repeats a block of code a specific number of times, or iterates over collections with for...of
and for...in
.
Use break
to exit early and continue
to skip the current iteration.
Syntax
// Counting loop
for (let i = start; i < end; i++) {
// body
}
// Iterate values from an iterable
for (const item of iterable) {
// use item
}
// Iterate keys from an object
for (const key in object) {
// use key, object[key]
}
Examples
// ১) থামুন / চলুন সহ গণনা
let যোগফল = 0;
প্রতি (let i = 1; i <= 10; i++) {
যদি (i === 5) চলুন; // ৫ স্কিপ
যদি (i > 8) থামুন; // ৯ পর্যন্ত
যোগফল += i;
}
কনসোল.লগ("যোগফল =", যোগফল);
// ২) for...of দিয়ে অ্যারে ও স্ট্রিং
const সংখ্যা = [2, 4, 6];
প্রতি (const n এর সংখ্যা) {
ছাপাও(n * n);
}
প্রতি (const ch এর "ABC") {
কনসোল.লগ(ch);
}
// ৩) for...in দিয়ে অবজেক্টের কী
const ব্যবহারকারী = { নাম: "রাফি", শহর: "Dhaka" };
প্রতি (const কী মধ্যে ব্যবহারকারী) {
কনসোল.তথ্য(কী, "=>", ব্যবহারকারী[কী]);
}
Notes
- Prefer
let
in loop headers so the index is block‑scoped. - Use
for...of
for array/iterable values; usefor...in
for object keys. - Avoid using
for...in
on arrays (order is not guaranteed). - Combine with
break
(exit) andcontinue
(skip) when needed.