🔁 Looping Through Arrays
Last Updated: 15th October 2025
When we store many values in an array, we often need to visit each element — for that we use loops.
Hinglish Tip 🗣: Array me jab kai items ho, loop har item par ek-ek karke kaam karta hai — print, check, modify, etc.
1. while loop
Use when the number of iterations depends on a condition.
const fruits = ["Apple", "Banana", "Cherry"];
let i = 0;
while (i < fruits.length) {
console.log(fruits[i]);
i++;
}
Hinglish Tip 🗣: while tab use karo jab aap condition pe depend kar rahe ho.
2. do-while loop
Runs the body once, then checks the condition.
const fruits = ["Apple", "Banana", "Cherry"];
let i = 0;
do {
console.log(fruits[i]);
i++;
} while (i < fruits.length);
3. for loop (classic)
- Most common and explicit way to iterate arrays.
- You control start, end, and step.
- Useful when you need the index for each element.
const fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
for...of loop (modern & simple)
Iterates values directly — clearer and less error-prone than index loops.Recommended for simple iterations.
const fruits = ["Apple", "Banana", "Cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
for ...in loop (less common)
Iterates Index directly.
const fruits = ["Apple", "Banana", "Cherry"];
for (const index in fruits) {
console.log(fruits[index]); // Apple, Banana, Cherry
}
💡 Quick Practice
- Use a for loop to print all elements of ["HTML","CSS","JS"].
- Exercises Set 1
- Exercises Set 2