Looping Through Arrays in JavaScript
JavaScript provides multiple ways to loop through arrays, ranging from traditional loops to modern high-level functions.
🔁 Using a for
Loop
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
➡️ Using for...of
Loop
for (const fruit of fruits) {
console.log(fruit);
}
💡 Using forEach()
Method
fruits.forEach(function(fruit, index) {
console.log(index + ": " + fruit);
});
🔍 map()
for Transformation
map()
creates a new array by transforming each element.
const upperFruits = fruits.map(fruit => fruit.toUpperCase());
console.log(upperFruits); // ["APPLE", "BANANA", "CHERRY"]
⚠️ Avoid for...in
with Arrays
for...in
is meant for objects. It loops over keys and can include inherited properties.
⚠️ Tip: Use
for...of
or forEach()
for clean array iteration.