How to Use map() in JavaScript: Syntax and Examples
In JavaScript,
map() is an array method that creates a new array by applying a function to each element of the original array. You use it by calling array.map(callback), where callback defines how each element is transformed.Syntax
The map() method is called on an array and takes a callback function as an argument. This function runs once for each element and returns a new value that forms the new array.
- array: The original array you want to transform.
- callback: A function that takes the current element, its index, and the whole array as arguments.
- The
map()method returns a new array with the results of calling the callback on each element.
javascript
array.map((element, index, array) => {
// return new value for new array
})Example
This example shows how to use map() to double each number in an array.
javascript
const numbers = [1, 2, 3, 4]; const doubled = numbers.map(num => num * 2); console.log(doubled);
Output
[2, 4, 6, 8]
Common Pitfalls
One common mistake is to use map() when you don't need the returned array, like when just looping for side effects. Also, forgetting to return a value inside the callback results in an array of undefined.
javascript
const nums = [1, 2, 3]; // Wrong: no return, results in undefined elements const wrong = nums.map(num => { return num * 2 }); console.log(wrong); // [2, 4, 6] // Right: return the value const right = nums.map(num => num * 2); console.log(right); // [2, 4, 6]
Output
[2, 4, 6]
[2, 4, 6]
Quick Reference
| Method | Description |
|---|---|
| array.map(callback) | Creates a new array by transforming each element with callback |
| callback(element) | Function applied to each element, returns new value |
| Returns | New array with transformed elements |
| Does not modify original array | Original array stays unchanged |
Key Takeaways
Use
map() to create a new array by transforming each element of an existing array.Always return a value inside the
map() callback to avoid undefined results.map() does not change the original array; it returns a new one.Avoid using
map() if you don't need the returned array; use forEach() instead.The callback receives the element, its index, and the original array as arguments.