The map method in JavaScript arrays invokes a provided function on each element of the array and generates a new array as a result. Importantly, this method does not modify the original array in any way.
Syntax
The syntax for the map function is illustrated as follows:
array.map(callback(currentvalue,index,arr),thisArg)
Parameter
callback - It denotes the function responsible for generating the new array.
currentvalue - The current element of array.
index - This parameter is not mandatory. It represents the position of the current element.
arr - This parameter is not mandatory. It refers to the array that the map function processes.
thisArg - This parameter is optional. It defines the value that will be utilized as 'this' during the execution of the callback function.
Return
An additional array is created where each element is derived from the output of a specified callback function.
JavaScript Array map method example
Let's see some examples of map method.
Example 1
In this context, the map function is utilized to round the specified elements to their closest integer value.
<script>
var arr=[2.1,3.5,4.7];
var result=arr.map(Math.round);
document.writeln(result);
</script>
Output:
Example 2
In this instance, the map function produces a new array by taking each element from the specified array and multiplying it by 3.
<script>
var arr=[2,4,6];
var result=arr.map(x=>x*3);
document.writeln(result);
</script>
Output:
6,12,18