Syntax
items.map((item, index, array) => result)Examples
Number the lesson list
Use the zero-based index to create labels without changing the original titles.
const lessons = ["Arrays", "Functions", "Objects"];
const labels = lessons.map((title, index) => `${index + 1}. ${title}`);
console.log(labels); // ["1. Arrays", "2. Functions", "3. Objects"]
console.log(lessons[0]); // ArraysReturn an updated object
Parentheses make the object literal an arrow-function result. Spreading each lesson copies its top-level properties; nested objects would still be shared.
const lessons = [{ title: "Arrays", minutes: 12 }];
const labelled = lessons.map(lesson => ({
...lesson,
duration: `${lesson.minutes} minutes`
}));
console.log(labelled[0].duration); // 12 minutes
console.log(labelled[0] === lessons[0]); // false
console.log(lessons[0].duration); // undefinedRemember the return inside braces
A block body needs return. Forgetting it creates undefined entries; it does not remove them.
const minutes = [5, 10];
const missing = minutes.map(value => { value * 2; });
console.log(missing); // [undefined, undefined]
const doubled = minutes.map(value => {
return value * 2;
});
console.log(doubled); // [10, 20]Parameters and values
- callback: Receives the item, its index and the original array. Its return value becomes the item at that position in the result.
- Return value: A new array with the input length captured when map() starts. Empty slots remain empty and are not passed to the callback. Returned objects may still share references with the input.
- thisArg (optional): A second argument sets this for a regular callback function. Arrow functions keep their surrounding this instead.
Best practices
- Use forEach() or a loop when you only want side effects and will not use a new array.
- Avoid changing the input inside the callback. map() does not mutate it automatically, but your callback can.
- For number strings, use values.map(value => Number.parseInt(value, 10)). Passing parseInt directly accidentally uses the array index as its radix.
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification