What is map in JavaScript: Explanation and Examples
map is a method used on arrays to create a new array by applying a function to each item of the original array. It does not change the original array but returns a new one with transformed values.How It Works
Imagine you have a list of items, like a basket of fruits, and you want to make a new basket where each fruit is sliced. The map method works like a machine that takes each fruit from the original basket, slices it, and puts the sliced fruit into a new basket. The original basket stays the same.
In programming terms, map takes a function you provide and runs it on every element of an array. It collects the results and returns a new array with these results. This way, you can easily transform data without changing the original list.
Example
This example shows how to use map to double each number in an array.
const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled);
When to Use
Use map when you want to create a new array by changing each item in an existing array. For example, you might want to convert a list of prices from dollars to euros, or extract just the names from a list of user objects. It is perfect when you need a one-to-one transformation of array elements without modifying the original array.
Key Points
- map returns a new array without changing the original.
- It applies a function to every element in the array.
- Useful for transforming data cleanly and simply.
- The function inside
mapreceives each element, its index, and the whole array.
Key Takeaways
map creates a new array by transforming each element of the original array.map for one-to-one changes like converting or extracting values.map runs on every element automatically.