map() Function is used to create a new array with the results from the function called.
Let us say, we have a Array that contains five numbers, 5, 8, 2, 81 and 9.
And we want to have an array with all the values with two added to it.
i.e. The first element 5 should be added with 2 and become 7.
Similarly, the second element 8 would be added with 2 and become 10.
Continuing this way, we should get an Array with the below values.
And map() helps us achieve the above array.
Let us see in the below example.
<html> <body> <script> function numberCheck(i) { return i+2 } var x = [5, 8, 2, 81, 9] var y = x.map(numberCheck) document.write(y) </script> </body> </html>
So, we have an Array that has 5 numbers.
And we want to construct an array with all the values incremented by 2.
We have defined a function called numberCheck(), that increments all the values by 2.
function numberCheck(i) { return i+2 }
And we have called the above function from map() function.
var y = x.map(numberCheck)
And map() function iterates 5 times(i.e. The length of the array), calling numberCheck() function.
var y = x.map(numberCheck)
And it increments all the values of the Array by 2 and forms a new Array.
And the new array is printed as output.
7,10,4,83,11