Open In App

JavaScript Index inside map() Function

Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, the map() method handles array elements, which creates a new array with the help of results obtained from the calling function for each and every array element in an array. The index is used inside the map() method to state the position of each element in an array, but it doesn’t change the original array. 

Syntax:

array.map(function(currentelement, index, arrayobj) {

  // Returns the new value instead of the item

});

Parameters: The Index inside function accepts three parameters as mentioned above and described below:

  • currentelement: The currentelement is a required argument in the map() which is the value of the current element.
  • index: The index is an optional argument map() which is an array index of provided current element.
  • arrayobj: The arrayobj is an optional argument in the map() which is the array object where the current element belongs. 

Example 1: The below example illustrates the Index inside the map() function:

Javascript




let student = ["Arun", "Arul",
    "Sujithra", "Jenifer",
    "Wilson"];
 
student.map((stud, index) => {
    alert("Hello... " + stud + "\n");
 
    let index = index + 1;
 
    alert("Your Position in Top 5"
        + " Rank is " + index + "\n");
});


Output:

  

Example 2: This example prints the values and index of the array elements using the above-described approach.

Javascript




let webname = ["welcome", "to",
    "GeeksforGeeeks"];
 
webname.map((web, index) => {
    document.write(web + "<br>");
});
 
// check in console
webname.map((web, index) => console.log(web, index));


Output:

welcome 0
to 1
GeeksforGeeeks 2

Supported Browsers: The browsers supported by the Index inside map() function are listed below:

  • Google Chrome
  • Internet Explorer
  • Firefox
  • Safari
  • Opera


Last Updated : 22 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads