JavaScript filter() Method: Select Elements by Condition

🚀 What is filter() in JavaScript? (Complete Guide for Developers) In JavaScript, filter() is a powerful array method used to create a new array by selecting elements that meet a specific condition. It does not modify the original array — instead, it returns a new filtered array. 📌 Syntax: array.filter((element, index, array) => { return condition; }); element → Current item being processed index (optional) → Index of the current element array (optional) → The original array 🔎 Simple Example: const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.filter(num => num % 2 === 0); console.log(evenNumbers); // Output: [2, 4, 6] 👉 Here, filter() returns only the numbers divisible by 2. 📦 Real-World Example (Filtering Objects): const users = [ { name: "Ali", active: true }, { name: "Sara", active: false }, { name: "Ahmed", active: true } ]; const activeUsers = users.filter(user => user.active); console.log(activeUsers); ✅ This is commonly used in: Search functionality Product filtering (e-commerce) Dashboard data filtering Status-based filtering 💡 Important Points: ✔ filter() does not change the original array ✔ It always returns a new array ✔ If no element matches → returns an empty array ✔ It works great with arrow functions 🆚 Difference from map() and forEach(): map() → transforms every element filter() → selects elements based on condition forEach() → executes logic but returns nothing 🎯 Why Every Developer Should Master filter(): Because modern web apps rely heavily on dynamic data manipulation — and filter() makes your code cleaner, readable, and functional-programming friendly. Clean code + Functional methods = Better performance & maintainability ✨ Are you using filter() in your projects? Drop your favorite use case below 👇 #JavaScript #FrontendDevelopment #WebDevelopment #Coding #100DaysOfCode

To view or add a comment, sign in

Explore content categories