Search code examples
javascript

Is it possible to return an empty slot from JavaScript's map() function?


This site has a similar question: Possible to push empty slot to an array? I want to know if it's possible for the Array.prototype.map callback to return an empty slot.

I tried this but it returns undefined instead:

console.log([1, 2, 3].map(() => {}));

I want to return empty slots so that I can simply call flat() on the return value to remove them. flat() does not remove undefined or null values.

I'm aware of the .filter(Boolean) trick, but I don't like that solution because 0 is falsey, and I've never intended to remove that as a side effect of removing null/undefined elements: in my experience, .filter(Boolean) is a ticking time bomb in one's code.


Solution

  • I want to know if it's possible for the Array.prototype.map callback to return an empty slot.

    No, this is not possible. A (callback) function always returns a value (or throws an exception), whereas an empty slot is "created" by the absence of a value. An empty slot is a property that does not exist despite being between 0 and the array's .length. The map() function always creates properties for the values returned from the calls to the callback function.