How to use JavaScript’s .map() method

The JavaScript method .map() lets you iterate through each element in an array and execute actions. A new array is created to store the results, leaving the original array intact.

What is JavaScript’s .map()?

JavaScript’s .map() method creates a new array by applying a callback function to each element of the original array. The method transforms each value from the original array, storing the result in a separate array. JS .map() is non-mutating, meaning that the original array remains unchanged.

The .map() method is often used for transforming all the elements in an array. For example, it can square elements, format text, filter objects and make a variety of other modifications. That makes .map() practical for making non-destructive changes to data, resulting in clean, coherent code.

What is the syntax for JavaScript .map()?

The syntax for JS .map() consists of a callback function on an array:

const newArr = originalArr.map(function(element, index, array) {
    // Code
});
javascript
  • originalArr: The array that .map() will be applied to
  • element: The current element being processed
  • index (optional): The index of the current element in the array
  • array (optional): The original array

Let’s look at an example.

const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(function(number) {
    return number * number;
});
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
javascript

The callback function that’s entered as an argument to .map() takes each element from the original array number and squares it. We then get a new array with the squares of each element from the original array.

Examples of JavaScript’s .map()

JavaScript’s .map() can be used to perform various operations on the elements of an array. Here are some of its most common use cases.

Filtering data

If you combine .map() with .filter(), you get an array that only contains values that are true for your chosen condition.

const numbers = [1, 2, 3, 4, 5];
const evenNumbersTimesTwo = numbers.filter(num => num % 2 === 0) .map(num => num * 2);
// Output: [4, 8]
javascript

In this example, the array numbers contains the values 1-5. We then apply the .filter() method. The filtering condition says that the number modulo 2 must be zero, which is only true of even numbers. This results in a new array, which only contains elements that are divisible by 2, giving us the array [2,4]. Next, we use the .map() method to double each element in the array. As a result, [2,4] becomes [4,8].

Rendering lists in JavaScript libraries

React is one of the most popular JavaScript frameworks and libraries, and .map()is useful for rendering lists in it. Note that React uses JSX syntax.

import React from "react";
import ReactDOM from "react-dom";
const colors = ["red", "green", "blue", "yellow", "orange"];
const ColorsList = () => (
    <div>
        <ul>{colors.map(color => <li key={color}> {color} </li>)}</ul>
    </div>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<ColorsList />, rootElement);
javascript

Above, we imported the models React and ReactDOM and created an array named colors with various color names. The React functional component ColorList uses .map() to create a <li> element for every color. The key attribute enables efficient updates with React. In the final step, the ColorsListcomponent is rendered in DOM with ReactDOM.render and the output is added to the DOM element with the ID root.

Formatting elements of an array

JavaScript’s .map() method is a simple way to format elements like strings.

const names = ["Alice", "Bob", "Charlie"];
const formattedNames = names.map(name => name.toLowerCase());
// Output: ["alice", "bob", "charlie"]
javascript

In this example, we combine .map() with the toLowerCase() method to convert each name into lowercase. The result is a new array called formattedNames, which contains the lowercase names. The original array names remains unchanged.

Web Hosting
Fast, scalable hosting for any website
  • 99.9% uptime
  • PHP 8.3 with JIT compiler
  • SSL, DDoS protection, and backups
Was this article helpful?
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.
Page top