Skip to content

JavaScript map function

  • by

JavaScript map function is available on only arrays. It creates a new array with the results of calling a function for every array element.

array.map(function(currentValue, index, array) {
  // return transformed value
}, thisArg);

The function takes three arguments:

  • currentValue: the value of the current element being processed.
  • index: the index of the current element being processed.
  • array: the array that the map() method was called upon.

JavaScript map function example

Simple example code using the map() function to square all the elements of an array:

<!DOCTYPE html>
<html>
<body>
  <script >
    const numbers = [1, 2, 3, 4, 5];

    const squaredNumbers = numbers.map(function(num) {
        return num * num;
    });

    console.log(squaredNumbers); // [1, 4, 9, 16, 25]

  </script>
</body>
</html>

Output:

JavaScript map function

Using map() for object elements in the array

The map() function can also be used to transform elements of an array that are objects.

const people = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Bob', age: 40 }
];

const peopleWithGreetings = people.map(function(person) {
  return { 
    name: person.name,
    greeting: `Hello, ${person.name}! You are ${person.age} years old.`
  };
});

console.log(peopleWithGreetings);

Output:

[
  { name: 'John', greeting: 'Hello, John! You are 25 years old.' },
  { name: 'Jane', greeting: 'Hello, Jane! You are 30 years old.' },
  { name: 'Bob', greeting: 'Hello, Bob! You are 40 years old.' }
]

Do comment if you have any doubts or suggestions

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading