JavaScript Index inside map() Function

To find an index of the current iterable inside the map() function in JavaScript, you can use the callback function’s second parameter, which is an index.

The index used inside the map() method indicates the position of each item in an array, but it does not modify the original array.

Syntax

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

});

Parameters

  • currentItem(required): The current element being processed in the array.
  • index(optional): The index of the current element being processed in the array.
  • arrayobj(optional): The array object where the current item belongs.

Return Value

Returns a new array

Visual Representation Visual Representation of JavaScript Index inside map() FunctionExample 1: How to Use Index inside map() Function

let arr = [5, 10, 15, 20, 25];

let doubledNumbers = arr.map((currentValue, index) => {
 console.log(`Index: ${index}, Value: ${currentValue}`);
 return currentValue * 2;
});

console.log(doubledNumbers);
console.log("Original Array: "+ arr);

Output

Index: 0, Value: 5
Index: 1, Value: 10
Index: 2, Value: 15
Index: 3, Value: 20
Index: 4, Value: 25
[ 10, 20, 30, 40, 50 ]
Original Array: 5,10,15,20,25

That’s it.

3 thoughts on “JavaScript Index inside map() Function”

  1. great guide but Map and map are different things in some places map is written as Map as it has different functions and does different things

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.