DEV Community

Aman Kumar
Aman Kumar

Posted on

# ๐Ÿ” From `forEach` to `filter`: Extracting Meaning from JavaScript Arrays

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);
});
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ Output:

js
ruby
java
python
cpp
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

โŒ 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);
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ Output:

[5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

โœ”๏ธ 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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ Output:

[5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”ง 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 },
];
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Filter Fiction Books Only

const fictionBooks = books.filter((book) => book.genre === "Fiction");

fictionBooks.forEach(book => console.log(book));
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ Output:

{ title: 'Book One', genre: 'Fiction', ... }
{ title: 'Book Six', genre: 'Fiction', ... }
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“š 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)