How does filter() work?
Short answer
filter() creates a new array containing only the elements for which the callback returns a truthy value; it doesn't mutate the original array.
Advertisement
AModel answer
filter() creates a new array containing only the elements for which the callback returns a truthy value; it doesn't mutate the original array.
const evens = [1,2,3,4].filter(n => n % 2 === 0); // [2,4]Real-world example
Filtering a product list to only show items currently in stock.
Likely follow-ups
- How would you filter out falsy values like 0 or an empty string?
Related topics