Quick Overview
`.filter()` keeps every element whose test returns truthy and hands back a new array, leaving the original untouched. A test that forgets to `return` filters everything out, because `undefined` is falsy.
The .filter() method creates a shallow copy of a portion of a given array, filtered down to just the elements that pass the test condition implemented by the provided callback function.
.filter() allows you to remove unwanted items or search array collections cleanly without writing manual for loops or mutating the source array.
Pass a callback function that returns true to keep an item, or false to discard it:
const scores = [45, 82, 91, 58, 76];
// Keep only passing scores (>= 70)
const passingScores = scores.filter((score) => score >= 70);
console.log(passingScores); // [82, 91, 76]
console.log(scores); // [45, 82, 91, 58, 76] (Original array untouched!)
Combine .filter() and .map() into a clean data processing pipeline:
const inventory = [
{ name: "Laptop", inStock: true, price: 999 },
{ name: "Phone", inStock: false, price: 500 },
{ name: "Monitor", inStock: true, price: 300 },
];
// Pipeline: Filter available items -> Map to uppercase names
const availableProductNames = inventory
.filter((item) => item.inStock)
.map((item) => item.name.toUpperCase());
console.log(availableProductNames); // ["LAPTOP", "MONITOR"]
.filter() callbacks should be pure test functions. Avoid mutating item properties inside the filter test!.filter() ALWAYS returns an array (even if 0 or 1 items match). If you want to find a single matching item, use .find().Write it yourself. The tests below run against your code.
Combine .filter() and .map() to clean data pipelines. Next, let's aggregate arrays into single values using .reduce()!
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.