.map()
.map() builds a new array with the result of calling a function on each item of the original array.
.map() walks through an array and calls your function once per item. Whatever the function returns goes into the same position of a new array. The result always has the same length as the original.
The original array does not change. That makes .map() a safe way to transform data: you get a converted copy and keep the source.
The function receives the item, and optionally the index: (item, index). It is usually written as an arrow function, as in lesson 01.02: pricesInCents.map((cents) => cents / 100).
In TypeScript, the type checker infers the type of the new array from what your function returns. Those types are gone when Node runs the code.
If you only want to do something with each item and not build an array, .forEach() is the more honest choice.
Reach for it when: you need to turn every item of an array into another value and keep a new list of the same size.
Examples
Common mistake
const numbers: number[] = [1, 2, 3]; const doubled: string[] = numbers.map((n) => n * 2); console.log(doubled);
Why: The function returns numbers, so `.map()` produces `number[]`, which does not fit a variable declared as `string[]`.
How to write it: Declare the right type (number[]) or return strings from the function, for example String(n * 2).
Common mistake
const numbers: number[] = [1, 2, 3];
const result = numbers.map((n) => {
n * 2;
});
console.log(JSON.stringify(result));Why: With braces, the arrow function needs `return`. Without it, it returns `undefined`, which JSON.stringify shows as `null`.
How to write it: Write return n * 2; or drop the braces: (n) => n * 2.
