JavaScript filter(): Select Elements with a Predicate
Quick answer
filter() returns a new dense array of present elements whose callback result is truthy. A predicate is a function used to decide whether an element qualifies.
How it works
The callback receives value, index and source. Accepted elements keep their original value and relative order. Ordinary missing positions are skipped. The initial length is captured, but later reads can observe mutations. Selected objects retain identity.
console.log([2, 9, 3, 10].filter(n => n >= 9).join(","));Expected output in Node.js:
9,10Only qualifying values are copied in order.
const a = [{stock: 0}, {stock: 2}];const b = a.filter(x => x.stock > 0);console.log(b.length, b[0] === a[1]);Expected output in Node.js:
1 trueFiltering preserves the selected object identity.
Common mistakes
Return a condition, not the transformed element unless its truthiness is the desired test. No matches means an empty array, not undefined.
Practice
Select in-stock items, then modify a selected record and explain the shared identity.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript filter(): Select Elements with a Predicate — Knowledge Check
Apply the taught concept and predict the output.
What happens if a filter predicate returns the number 2?
What is returned when no present elements satisfy the predicate?
Which order do accepted elements have in an ordinary filter result?
What is the exact console output in JavaScript filter(): Select Elements with a Predicate example 1?
console.log([2, 9, 3, 10].filter(n => n >= 9).join(","));What is the exact console output in JavaScript filter(): Select Elements with a Predicate example 2?
const a = [{stock: 0}, {stock: 2}];const b = a.filter(x => x.stock > 0);console.log(b.length, b[0] === a[1]);