How to Map Array Elements in JavaScript

To map an array of elements in JavaScript, you can use the “array.map()” function. The array.map() is a pure built-in function that creates a new array populated with the results of calling a provided function on every item in the calling array. It creates a new array by calling a function for every array element.

The map() does not execute the function of every item. This is because the map() does not change an original array, and that’s why it is a pure function.

Syntax

array.map(function(current value, index, array), this value)

Arguments

  1. function(): It is a function for each array element.
  2. current value: It is a value of the current element.
  3. index: It is an index of the current element.
  4. array: The array for the current element.
  5. this value is passed to the function to be used as its value.

Return value

          It is an array resulting from a function for each array element.

          Example

          const num = [10, 20, 30, 40, 50]
          const newarr = num.map(myfun)
          
          function myfun(n) {
           return n * 10;
          }
          
          console.log(newarr);

          Output

          [ 100, 200, 300, 400, 500 ]

          In this example, you can see that we are multiplying each element by 10 using the array.map() function. The map() function calls a provided CALLBACK FUNCTION once for each item in an array, in order, and constructs a new array from the results.

          That’s it for this tutorial.

          Leave a Comment