When working with arrays in JavaScript, you're often filtering, looping, or performing operations on each element. But when should you use forEach()
and when should you use filter()
?
Letโs walk through practical examples to understand their differences, how they behave, and what they're best at.
๐ Looping with forEach()
const coding = ["js", "ruby", "java", "python", "cpp"];
coding.forEach((item) => {
console.log(item);
});
๐งพ Output:
js
ruby
java
python
cpp
forEach()
simply loops through each element in the array and executes a function.
But here's a catch: It doesn't return anything.
๐ค What if you try to return a value?
const values = coding.forEach((item) => {
return item;
});
console.log(values); // Output: undefined
โ Even with a return inside,
forEach()
does not return a new array.
It's useful only for side effects, like printing, updating UI, or pushing into another array.
๐ Enter filter()
โ the Selector
What if you want to extract a subset of an array? Thatโs where filter()
shines.
const myNums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const numbersGreaterThanFour = myNums.filter((num) => num > 4);
console.log(numbersGreaterThanFour);
๐งพ Output:
[5, 6, 7, 8, 9, 10]
โ๏ธ
filter()
returns a new array containing only elements that satisfy the condition.
โ๏ธ Block Syntax (with return
)
const numbers = myNums.filter((val) => {
return val > 4;
});
console.log(numbers);
Same output, just written with explicit return.
๐ forEach
vs filter
in Practice
Letโs try doing what filter
does, but using forEach
:
const newNums = [];
myNums.forEach((num) => {
if (num > 4) {
newNums.push(num);
}
});
console.log(newNums);
๐งพ Output:
[5, 6, 7, 8, 9, 10]
๐ง Works fine, but notice how you have to manually manage the new array.
filter()
makes this cleaner and declarative.
๐ Real World Example: Filtering Books by Genre
const books = [
{ title: 'Book One', genre: 'Fiction', publish: 1981, edition: 2004 },
{ title: 'Book Two', genre: 'Non-Fiction', publish: 1992, edition: 2008 },
{ title: 'Book Three', genre: 'History', publish: 1999, edition: 2007 },
{ title: 'Book Four', genre: 'Non-Fiction', publish: 1989, edition: 2010 },
{ title: 'Book Five', genre: 'Science', publish: 2009, edition: 2014 },
{ title: 'Book Six', genre: 'Fiction', publish: 1987, edition: 2010 },
{ title: 'Book Seven', genre: 'History', publish: 1986, edition: 1996 },
{ title: 'Book Eight', genre: 'Science', publish: 2011, edition: 2016 },
{ title: 'Book Nine', genre: 'Non-Fiction', publish: 1981, edition: 1989 },
];
๐ Filter Fiction Books Only
const fictionBooks = books.filter((book) => book.genre === "Fiction");
fictionBooks.forEach(book => console.log(book));
๐งพ Output:
{ title: 'Book One', genre: 'Fiction', ... }
{ title: 'Book Six', genre: 'Fiction', ... }
๐
filter()
is amazing when you're querying data โ like filtering by genre, year, or other criteria.
๐ง Final Thoughts
Function | Purpose | Returns a New Array? | Use When... |
---|---|---|---|
forEach() |
Executes a function for each item | โ No | You're just doing something with each item |
filter() |
Filters items based on a condition | โ Yes | You need to extract a subset of data |
Top comments (0)