JavaScript Tutorial in Hindi #10 | For Loop in JavaScript (2025)
Why Use for
Loops with Arrays?
Sometimes, forEach()
, map()
, or filter()
are great — but if you want:
- To break the loop early
- To skip specific indexes
- To use custom logic
- Or you're just more comfortable with loops
Then traditional loops like for
, while
, or for...of
are perfect!
🔁 1. Classic for
Loop
javascript
CopyEdit
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(`Index ${i}: ${fruits[i]}`);
}
- ✅ Full control over index
- ✅ Can break or continue
- ✅ Great for modifying arrays in-place
🔁 2. for...of
Loop
javascript
CopyEdit
for (const fruit of fruits) {
console.log(fruit);
}
- ✅ Cleaner syntax
- ❌ Can't access index directly (but you can combine with
.entries()
if needed)
javascript
CopyEdit
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit);
}
🔁 3. while
Loop
javascript
CopyEdit
let i = 0;
while (i < fruits.length) {
console.log(fruits[i]);
i++;
}
- ✅ Used when you're unsure of loop count ahead of time