⬅ Previous Topic
Iterating over Objects in JavaScriptNext Topic ⮕
Spread and Rest Operators in JavaScript⬅ Previous Topic
Iterating over Objects in JavaScriptNext Topic ⮕
Spread and Rest Operators in JavaScriptIterating over arrays is a common task in JavaScript. Whether you're printing values, modifying items, or transforming data, it's crucial to know how to efficiently loop through arrays.
In this topic, you'll learn different ways to iterate over arrays including for
, for...of
, forEach()
, and map()
. Each method has its own use-case, and we'll explore them with examples.
for
LoopThe traditional for
loop gives you full control over the iteration process. It's useful when you need to access both the index and the value.
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]);
}
Output:
0 apple 1 banana 2 cherry
Question: What if you want only the values, not the index?
Answer: Use a for...of
loop or forEach()
if you don’t need the index.
for...of
LoopThe for...of
loop was introduced in ES6 and is great when you just want to access the values of an array.
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
Output:
red green blue
forEach()
MethodThe forEach()
method executes a provided function once for each array element. It’s very readable and commonly used in modern JavaScript.
const numbers = [10, 20, 30];
numbers.forEach(function(number, index) {
console.log(`Index ${index}: Value ${number}`);
});
Output:
Index 0: Value 10 Index 1: Value 20 Index 2: Value 30
map()
for TransformationThe map()
method creates a new array populated with the results of calling a provided function on every element. Use this when you need to return new values.
const prices = [100, 200, 300];
const discounted = prices.map(price => price * 0.9);
console.log(discounted);
Output:
[90, 180, 270]
Question: Can you use map()
for side effects like console.log
?
Answer: Technically yes, but it’s a bad practice. Use forEach()
for side effects and map()
for transformations.
while
and do...while
LoopsThese are general-purpose loops, less common for array iteration but still useful in certain scenarios.
const animals = ["dog", "cat", "rabbit"];
let i = 0;
while (i < animals.length) {
console.log(animals[i]);
i++;
}
Output:
dog cat rabbit
for
– Full control, index + valuefor...of
– Cleanest for value iterationforEach()
– Best for side effects like loggingmap()
– Best for transforming values into a new arraywhile
– Good for custom conditions or unknown lengthTry iterating over this array in three different ways: ["sun", "moon", "stars"]
. Print each value prefixed with "Celestial:".
Understanding array iteration is fundamental to JavaScript programming. Choose the right loop based on your need—whether it’s transformation, side effects, or index access.
⬅ Previous Topic
Iterating over Objects in JavaScriptNext Topic ⮕
Spread and Rest Operators in JavaScriptYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.