filter: Selecting Elements in JavaScript
filter keeps elements passing a predicate: [1,2,3,4].filter(x => x % 2 === 0) is [2,4]. Like map it returns a fresh array without touching the input; unlike map, output length varies (possibly zero). The predicate sees (value, index, array) for positional rules.
filter-then-map chains read as pipelines (actives.filter(...).map(...)), and combining with Boolean removes all falsy values in one idiom (arr.filter(Boolean)). For first-match-only needs, find() stops early instead of scanning everything.
Keep what passes
Truth-returning elements survive in order; the rest vanish β output is a subset, possibly empty.
Pure like map
Input untouched, fresh array returned β safe to chain and re-run.
filter(Boolean) cleans
Drops all eight falsy values at once β the standard null/empty scrubber.
find for first-only
Need one match, not all? find() stops at the first hit instead of scanning the tail.
let nums = [1, 2, 3, 4, 5];let evens = nums.filter(n => n % 2 === 0);console.log(evens, evens.length);Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself β building beats watching.