JavaScript Array map() Method with Example

In this tutorial, we will learn about the JavaScript Array map() method with the help of example programs.

Array.map() method simply iterates over each element in an array, invokes a callback function for each element, and returns the result of each function call in a new array.

In other words, the map() method goes through the entire array, calls the function on each element, and builds a new array with return values of that function.

In contrast to forEach(), the map() creates and returns a new array that contains the value returned by the callback function. It makes the copy of the original array.

The forEach() method simply executes a function for each element. It does not care about what we are returning from the callback function. It does not make the copy of original array.

The callback function takes three parameters that are as:

  • the value of current element in the array.
  • the index of current element in the array.
  • a reference to array itself.

Consider the following example below.

Program code 1:

<script>
  let numbers = [2, 3, 4, 5, 6];
// Create a function to return the cube of a number.
  function cube(num) {
     return num * num * num;
   }
// Call the cube() function to each value (element) in the given array.
   let cube_numbers = numbers.map(cube);
   document.write("New array: " +cube_numbers);
</script>
Output:
      New array: 8,27,64,125,216

The return value can be based on the arguments passed to the callback function. In the above example, each number in the array is mapped to the cube of itself in a new array.

The returned value by the callback is just string. We can use any name for parameters. In the above example, we use num to represent every element in the array.

Since the callback function only needs the value of each element, therefore, we only need to provide the parameter.

Array.prototype.map() method was added in ES5 and is mostly used to iterate over elements of an array.

JavaScript Array map() Method Syntax


The general syntax of the forEach() method in JavaScript is as:

// Arrow function
  arr.map((element) => { /* ... */ })
  arr.map((element, index) => { /* ... */ })
  arr.map((element, index, array) => { /* ... */ })

// Callback function
  arr.map(callbackFn)
  arr.map(callbackFn, thisArg)

// Inline callback function
  arr.map(function(element) { /* ... */ })
  arr.map(function(element, index) { /* ... */ })
  arr.map(function(element, index, array){ /* ... */ })
  arr.map(function(element, index, array) { /* ... */ }, thisArg)

Here, arr is the name of an array on which map() method will invoke.

map() Parameters


The map() method may take three parameters that are as:

  • callbackFn – The function to execute on each array element. Each time callbackFn executes, the map() method adds the returned value to the new array. It can be called with the following arguments:
    • element – The current element to be processed in the array.
    • index – The index of an element in the array.
    • array – The array on which map() method is called.
  • thisArg – Value to use as this when executing the callback function. It is an optional and is undefined by default.

map() Return Value


The map() method creates and returns a new array containing the values returned by callback function.


Notes:

  • The map() method does not change the original array.
  • It runs callback once for every array element in order.
  • It does not run callback function for array elements without values.

Mapping an array of numbers to an array of cube roots


Let’s create a JavaScript program in which we will take an array of numbers and create a new array containing the cube roots of the numbers of the original array.

Program code 2:

<script>
  const numbers = [1, 8, 27, 64, 125 ];
// Create a function to return the cube root of a number.
  function cubeRoot(num) {
    let cubeR = Math.cbrt(num);
    return cubeR;
  }
// Call the cubeRoot() function to each value (element) in the given array.
   let cubeR_numbers = numbers.map(cubeRoot);
   document.write("New array: " +cubeR_numbers);
</script>
Output:
      New array: 1,2,3,4,5

In the preceding example, we have called map() method on the array numbers. Every number will pass one by one in order to the callback function cubeRoot(). The map() method then maps the returned value by that callback function into a new array.


Let’s take another example in which we will take an array of numbers and create a new array containing the square of the numbers in the original array. Here, we will create an arrow function and an anonymous function.

Program code 3: using arrow function

<script>
  const numbers = [2, 4, 6, 8, 10];
  const squaredNums = numbers.map(num => num * num);
  document.write("New array: " +squaredNums);
</script>
Output:
      New array: 4,16,36,64,100

Program code 4: using anonymous function

<script>
  const numbers = [2, 4, 6, 8, 10];
  const squaredNums = numbers.map(function(num) {
     return num * num;
  });
  document.write("New array: " +squaredNums);
</script>
Output:
      New array: 4,16,36,64,100

Reformat objects in an array using map() Method


Let’s create a JavaScript program in which we will take an array of objects and create a new array containing the newly reformatted objects.

Program code 5:

<script>
  let kvArr = [{ key: 1, value: 10 },
                { key: 2, value: 20 },
                { key: 3, value: 30 }
              ];

 let reformattedArr = kvArr.map(({ key, value}) => ({ [key]: value }));
 document.write(reformattedArr);
</script>
Output:
      [ { '1': 10 }, { '2': 20 }, { '3': 30 } ]

Object elements in Array using map() Method


Let’s create a JavaScript program in which we will take an array of employee objects containing name, salary, and bonus. Then, we will create objects of a new array containing name, and net salary. Look at the following JavaScript code to understand better.

Program code 6:

<script>
 let employees = [
      { name: "John", salary: 10000, bonus: 500 },
      { name: "Bob", salary: 15000, bonus: 700 },
      { name: "Adam", salary: 20000, bonus: 900},
      { name: "Sonam", salary: 15000, bonus: 700 },
  ];
// calculate the net salary given to all employees.
   let calSalary = (obj) => {
   newObj = {};
   newObj.name = obj.name;
   newObj.netSalary = obj.salary + obj.bonus;
   return newObj;
  };
  let newArr = employees.map(calSalary);
  document.write(newArr);
</script>
Output:
      [ { name: 'John', netSalary: 10500 },
       { name: 'Bob', netSalary: 15700 },
       { name: 'Adam', netSalary: 20900 },
       { name: 'Sonam', netSalary: 15700 } ]

Try It Yourself

Program code 7:

<script>
  let numbers = [1, 4, 9];
  let doubleNumbers = numbers.map((num) => num * 2);
  document.write(doubleNumbers);
</script>

When not to use map() method in JavaScript?


We know that the map() method creates and returns a new array containing the returned value by callback function. It does not change the original array.

If you are not planning to use the returned array, then using the map() is an anti-pattern. Therefore, use forEach() or for…of instead.

You shouldn’t be using map() method if:

  • you’re not using the new array that map returns.
  • you do not want to use returning values from the callback.

In this tutorial, you learned JavaScript array map() method with many example programs. You also understood what is the basic difference between forEach() and map() and when to use it. Hope that you will have understood the basic concept of array map() method and practiced all programs.
Thanks for reading!!!
Next ⇒ JavaScript array filter() method⇐ Prev Next ⇒