How Does filter() Work? Finding the Products You Actually Need
Quick Overview
The .filter() method evaluates every element in an array against a boolean test condition. It returns a new array containing only the elements that evaluate to true.
The Real-World Story: The Security Guard at VIP Club
Imagine a line of 100 people waiting to enter a VIP tech lounge. The security guard at the door has a specific rule: "Only people wearing a VIP wristband AND over age 18 can enter."
The guard inspects each person one by one. If they meet both criteria, they step into the lounge (New Array). If they don't, they are filtered out. The original crowd outside remains unaffected. That is .filter() in action.
Step-by-Step Code Example
const courses = [
{ id: 1, title: "JavaScript Fundamentals", category: "JS", isPublished: true },
{ id: 2, title: "Advanced Python", category: "Python", isPublished: true },
{ id: 3, title: "Draft Draft Course", category: "JS", isPublished: false }
];
// Filtering published JavaScript courses only
const visibleJsCourses = courses.filter(
(course) => course.category === "JS" && course.isPublished === true
);
console.log(visibleJsCourses);
// Returns Array with only 1 item: "JavaScript Fundamentals"What I Learned
Combining .filter() followed by .map() is one of the most common power patterns in frontend development for building instant search bars and category filters!