How do you write a polyfill for filter in JavaScript?
Add a method to Array.prototype that loops through the array, calls the callback with (element, index, array), and pushes the element to a result array if the callback returns truthy. Return the result array.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Writing Polyfills for filter and reduce in JavaScript
Handle the initial value: if provided, start with it at index 0; if not, use the first element and start at index 1. Loop through, calling callback(accumulator, element, index, array). Return the final accumulator. Throw TypeError for empty arrays without an initial value.
Because without an initial value, reduce uses the first element as the accumulator. An empty array has no first element, so the spec throws TypeError: Reduce of empty array with no initial value.
Four arguments: the accumulator, the current element, the current index, and the array itself. Most callbacks only use the first two, but the polyfill should pass all four to match the spec.
Still have questions?
Browse all our FAQs or reach out to our support team
