- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Array map
JavaScript Arrays
JavaScript Array map
JavaScript
mapbuilds a new array by running a function on every element.
The new array always has the same length as the original.
The original array is never changed.
Example
Example
javascript
const numbers = [1, 2, 3];
console.log(numbers.map(n => n * 2).join(","));The output is 2,4,6.
What is map?
map transforms every element into something else.
Whatever the callback returns becomes the element in the new array.
It is the right choice whenever you want a list of the same length in a different shape.
Syntax
Syntax
javascript
const result = array.map(function (value, index) {
return newValue;
});The callback must return a value, or you get undefined.
Transforming Values
The callback decides what each element becomes.
Example
Example
javascript
const prices = [100, 200];
console.log(prices.map(p => p * 1.2).join(","));Each price now includes 20 percent tax.
Using the Index
The second argument is the position.
Example
Example
javascript
const names = ["Ada", "Grace"];
console.log(names.map((name, i) => (i + 1) + ". " + name).join(" | "));Here the index is used to number the list.
Pulling One Property Out
This is one of the most common uses of map.
Example
Example
javascript
const users = [{ name: "Ada" }, { name: "Grace" }];
console.log(users.map(u => u.name).join(","));An array of objects becomes an array of names.
The Missing return
With braces, the callback must return something.
Forgetting it gives an array full of undefined.
Example
Example
javascript
const numbers = [1, 2, 3];
console.log(numbers.map(n => { return n * 2; }).join(","));Without the return the output would be ,, instead.
map or forEach?
Use map when you want a new array.
Use forEach when you just want to do something with each element.
Example
Example
javascript
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
console.log(numbers.join(","));
console.log(doubled.join(","));The original is unchanged and the new array holds the results.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript map</title>
</head>
<body>
<h1>JavaScript map</h1>
<p id="result"></p>
<script>
const prices = [100, 250, 400];
const withTax = prices.map(p => p * 1.2);
document.getElementById("result").innerHTML = withTax.join(", ");
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try a discount instead:
Change 1.2 to 0.9 to take 10 percent off.
Important Points
mapreturns a new array of the same length.- The callback's return value becomes the new element.
- The original array is not changed.
- A callback with braces must include
return. - Use
mapfor results andforEachfor side effects.
Conclusion
map is the standard way to transform a list in JavaScript.
It replaces a loop, a new array, and a push with one readable line.
It is probably the array method you will use most often.
