One of the first hurdles in JavaScript is learning how to manage collections of data. For example, say you have several products, numbers, or user records. How do you check or modify each of them without writing repetitive code? The answer lies in loops.
In this guide, we’ll look at the various methods you can use to loop through arrays and objects in JavaScript. If you’re new to coding, don’t worry, we’ll go slowly, explain each concept in plain language, and show practical examples you can follow along with.
What You’ll Learn
By the end of this guide, you’ll understand:
- The difference between arrays and objects.
- How to loop through arrays using different methods.
- How to loop through objects and access their data.
- When to use each looping method (
for
,forEach
,map
,filter
,reduce
,find
). - Best practices for choosing the right loop as a beginner.
Understanding Arrays vs. Objects
Before we start learning about loops, it’s important to understand the type of data we’ll be working with.
Arrays: These are ordered lists. Think of them as numbered shelves where each item has an index (position).
Example:
const fruits = ["apple", "banana", "orange"];
Objects: A way to organize data as key-value pairs, where each key points to a specific value.
const user = { name: "Wisdom",
age: 30,
role: "Developer" };
Arrays are best for lists, while objects are best for describing something with named properties.
Now let’s learn how to loop through them.
Looping Through Arrays
- The for Loop (the classic way)
A for
loop is the most common traditional approach for stepping through array elements. It uses an index to access each item.
const fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]); // apple, banana, orange
}
It’s helpful for beginners since it demonstrates how loops function behind the scenes. Also useful when you need the index or want to stop early.
-
forEach()
(a simpler approach)
If you don’t care about the index and just want to “do something” for each item, forEach()
is cleaner.
fruits.forEach(fruit => {
console.log(fruit);
});
Easier to read than a for loop, but you can’t stop it early with break.
-
map()
(transforming values)
Use map()
when you want to create a new array by applying a transformation.
const uppercased = fruits.map(fruit => fruit.toUpperCase());
console.log(uppercased); // ["APPLE", "BANANA", "ORANGE"]
Think “transform”: each element becomes something new.
-
filter()
(picking specific items)
Sometimes, you only want certain elements from an array.
const longNames = fruits.filter(fruit => fruit.length > 5);
console.log(longNames); // ["banana", "orange"]
Think “selection”: it gives you a smaller array.
- find() (first match only)
Use find() if your goal is to return just the first item that satisfies the given condition.
const firstFruit = fruits.find(fruit => fruit.startsWith("b"));
console.log(firstFruit); // "banana"
It is faster when you don’t need all matches, but just the first one.
-
reduce()
(combine into one value)
The most powerful one. reduce()
lets you take an array and “reduce” it into a single result.
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 10
Use when you want totals, averages, or combined results.
Looping Through Objects
Objects aren’t ordered like arrays, so we loop through their keys and values.
-
for...in
(basic way)
const user = { name: "Wisdom", age: 30, role: "Developer" };
for (let key in user) {
console.log(key, user[key]);
}
It works fine, but because it includes inherited properties, it’s not always the safest option for beginners.
-
Object.keys()
,Object.values()
,Object.entries()
A safer and more modern approach is to convert objects into arrays.
Object.keys(user).forEach(key => console.log(key, user[key]));
// name Wisdom, age 30, role Developer
Object.values(user).forEach(value => console.log(value));
// Wisdom, 30, Developer
Object.entries(user).forEach(([key, value]) => console.log(key, value));
// name Wisdom, age 30, role Developer
These methods are beginner-friendly and predictable.
Putting It All Together (Practical Example)
Let’s say we have a list of products. We want to:
- Find products in stock.
- Calculate their total value.
const products = [
{ name: "Pen", price: 1.5, qty: 10 },
{ name: "Book", price: 12, qty: 2 },
{ name: "Notebook", price: 5, qty: 0 }
];
const totalValue = products
.filter(p => p.qty > 0) // only in stock
.map(p => p.price * p.qty) // calculate value
.reduce((sum, value) => sum + value, 0); // total
console.log(totalValue); // 39
By applying
filter
, thenmap
, and finallyreduce
, we created a flow where each method contributes to the next, keeping the code readable.
Best Practices for Beginners
- Start with the method that matches your goal (transform:
map
, select:filter
, total:reduce
). - Use
forEach
for simple side tasks like logging. - Use
for
orfor...of
when you need to stop early. - For objects, prefer
Object.keys/values/entries
overfor...in
. - Don’t stress about performance yet; focus on writing clear, understandable code.
Conclusion
Loops are at the heart of JavaScript programming. For beginners, the most important step is choosing the right method for the job:
- Use
for
andfor...of
when learning the basics. - Move to array methods (
forEach
,map
,filter
,find
,reduce
) as you get more comfortable. - For objects, stick with
Object.keys
,Object.values
, andObject.entries
to keep things simple.
Practice these techniques on small problems, and soon you’ll find that looping through data feels natural and effortless. As you progress, you’ll find that both small and complex projects depend heavily on these looping patterns.
You can reach out to me via LinkedIn
Top comments (0)