The javascript map()
function1 takes in a callback function, applies that callback function to each element of an array, and returns a new array containing the results. Many languages have a map
function, and they all behave roughly this way2.
Javascript map basics
map()
accepts a single callback function, and passes each element of the calling array into that function:
const myArray = [1,2,3];
const timesTen = myArray.map(item => item * 10);
console.log(timesTen);
// [10, 20, 30]
Important note: don’t forget to return
something, otherwise you’ll end up with a new array containing all undefined
values:
const myArray = [1, 2, 3];
const timesTen = myArray.map((item) => {
console.log(item * 10);
});
// 10
// 20
// 30
// We never returned anything
console.log(timesTen);
// [undefined, undefined, undefined]
Or maybe you have a more complicated function you want to use in your map
. You can define it elsewhere and just pass it in like this, assuming it accepts a single parameter:
import { fancyFunction } from "~/utils";
const myArray = [1, 2, 3];
// Like any array method, you can pass your callback this way
const fancyArray = myArray.map(fancyFunction);
Map’s additional arguments
Typically when using map()
, the callback function only takes in a single argumentโthe current array element. However, map
actually makes three arguments available to the callback: the current array element, its index in the array, and the full calling array (which is the same every time).
Let’s look:
const myArray = ["a", "b", "c"];
myArray.map((element, idx, arr) => console.log(element, idx, arr));
// a 0 ["a", "b", "c"]
// b 1 ["a", "b", "c"]
// c 2 ["a", "b", "c"]
That’s about it. I hope this was helpful.
Helpful Links
- Array.prototype.map – Moz docs
- Javascript’s map object – Moz docs
Notes
- Not to be confused with javascript’s Map object โฉ๏ธ
- Python’s
map
leaves something to be desired, but you can just use list comprehensions instead โฉ๏ธ