So many times I learn or correct my knowledge of things when I'm doing code reviews. TIL that I was under the incorrect assumption that map() would skip over null or undefined array entries. I was wrong. It makes sense in hindsight. Especially since it's in the first line of the documentation. 🤦♀️
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const original = ["a", null, "b", undefined];
const mapped = original.map((item) => Boolean(item));
I was thinking it would do this: true,true
I was wrong: true,false,true,false
Top comments (5)
It only skips over non-enumerable values, e.g. in sparse Arrays:
Ok, that makes total sense and that kind of idea was probably how I ended up assuming incorrectly. There IS another option for "nothing" other than
nullandundefinedin an array. Also, I just learned you could map aconsole.log. Two TIL for the price of one!You can pass basically any function as the callback to
map, but if the callback itself returnsundefined(likeconsole.logdoes) the resulting array won't be very useful. In that case, it becomes basically the same asforEach, because the side effects of the callback still happen.This is less about
.mapthan aboutconsole.log. If you want to know what argument a callback receives, you can just drop in console.log and will instantly see them. A neat trick for introspection.Definitely, I thought it was an elegant shortcut to having to do a
mapthenconsole.logfor example purposes.