JavaScript arrays are more powerful than they seem at first glance. Today, I dove into five powerful methods that make working with arrays clean, expressive, and efficient. Here's a quick summary of what I learned about forEach
, map
, filter
, reduce
, and find
.
1. forEach()
– Just Loop Through It
forEach
is used to run a function once for each item in the array.
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach((fruit, index) => {
console.log(`${index + 1}. ${fruit}`);
});
Use case: When you just want to iterate and do something — like logging, updating the DOM, etc.
Note: It doesn't return anything (always undefined
).
2. map()
– Transform Every Element
map
creates a new array by applying a function to every item.
const numbers = [1, 2, 3];
const squared = numbers.map(num => num * num);
console.log(squared); // [1, 4, 9]
Use case: When you want to transform data without changing the original array.
3. filter()
– Keep What You Need
filter
returns a new array containing only the elements that match a condition.
const ages = [12, 18, 21, 16, 30];
const adults = ages.filter(age => age >= 18);
console.log(adults); // [18, 21, 30]
Use case: When you want to exclude certain elements based on a condition.
4. reduce()
– Boil It Down to One Value
reduce
is powerful and flexible. It takes a function and reduces the array to a single value.
const numbers = [10, 20, 30];
const total = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(total); // 60
Use case: When you want to compute a single value like sum, average, or even build a new object or array.
5. find()
– Stop at the First Match
find
returns the first element that matches a condition.
const users = [
{ id: 1, name: 'Ram' },
{ id: 2, name: 'Shyam' },
];
const user = users.find(user => user.id === 2);
console.log(user); // { id: 2, name: 'Shyam' }
Use case: When you're looking for one specific item in an array.
Quick Summary
Method | Returns | Use For |
---|---|---|
forEach |
undefined |
Side effects (logging, modifying DOM) |
map |
New Array | Transforming data |
filter |
New Array | Selecting certain items |
reduce |
Any Value | Reducing to one value (sum, object) |
find |
First Match | Searching for a specific item |
Final Thoughts
Learning these array methods helped me understand how expressive and functional JavaScript can be. They make code more readable, concise, and easier to maintain.
Top comments (2)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.