DEV Community

Lisa Dean
Lisa Dean

Posted on

TIL: A Basic Thing about map()

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. 🤦‍♀️

MDN Docs

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 
Enter fullscreen mode Exit fullscreen mode

Discussion (5)

Collapse
lexlohr profile image
Alex Lohr

It only skips over non-enumerable values, e.g. in sparse Arrays:

const array = [];
array[8] = true;
array.map(console.log);
// true,  8,  [, , , , , , , , true]
Enter fullscreen mode Exit fullscreen mode
Collapse
lisadean profile image
Lisa Dean Author

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 null and undefined in an array. Also, I just learned you could map a console.log. Two TIL for the price of one!

Collapse
lionelrowe profile image
lionel-rowe • Edited on

You can pass basically any function as the callback to map, but if the callback itself returns undefined (like console.log does) the resulting array won't be very useful. In that case, it becomes basically the same as forEach, because the side effects of the callback still happen.

Thread Thread
lexlohr profile image
Alex Lohr

This is less about .map than about console.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.

Thread Thread
lisadean profile image
Lisa Dean Author

Definitely, I thought it was an elegant shortcut to having to do a map then console.log for example purposes.