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:

  1. To break the loop early
  2. To skip specific indexes
  3. To use custom logic
  4. 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]}`);
}
  1. ✅ Full control over index
  2. ✅ Can break or continue
  3. ✅ Great for modifying arrays in-place

🔁 2. for...of Loop

javascript
CopyEdit
for (const fruit of fruits) {
console.log(fruit);
}
  1. ✅ Cleaner syntax
  2. ❌ 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++;
}
  1. ✅ Used when you're unsure of loop count ahead of time