I have an array with some empty elements in it and I am calling .filter on that array with a callback that always returns true.
[1, 2, , 5].filter(() => true);
The result of the above code is [1, 2, 5] - the empty element is no longer there. This isn't what I'd expect, because the callback returns true.
For comparison, Array.prototype.map does execute the callback for empty items:
[1, 2, , 5].map(x => x); // returns [1, 2, , 5]
In map, the callback is not called for each element (as you can see by logging the value inside the callback to map), but keys are preserved, leaving the empty slots in the result. Filter does not preserve keys (as filtering often shifts keys around), so those are lost. Neither operation actually runs the callback on empty slots, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With