How to use the map method to loop through an array in JavaScript

Overview

The map() method returns the new array after processing each element for the given array.

It accepts a callback function, which has currentItem as a mandatory parameter. We can hold this currentItem and process it as we like.

Syntax

const newArrayName = oldArray.map(callbackFun(currentItem, currentIndex, array))

Parameters

The map() method takes callbackFun as a parameter, and this callback function takes currentItem, currentIndex, and an array as parameters.

Return value

The map() method returns a new array with each element resulting from the callback function.

Example

Let's look at an example of using the map to loop through an array. In the following example, we'll get the square of each number present inside the array.

Code

Let's look at the code below:

const nums = [1, 2, 3, 4];
// pass a callback function to map
const squares = nums.map(x => x ** 2);
console.log(squares);

Explanation

In the above code snippet:

  • Line 1: We declare and initialize an array nums.
  • Line 4: We loop through the array nums using the map() method and calculate the square of each element in the array nums. We then store the returned new array in the variable squares.
  • Line 6: We print the new array squares to the console.

Free Resources