Language:

Search

49. map() in JavaScript

  • Share this:

The map() method is used for creating a new array by applying a provided function to each element in an existing array.
Essentially, it allows you to transform each element in an array and store the results in a new array,
while keeping the original array unchanged.

Example 1:

<script>
  const numbers = [1, 2, 3, 4, 5];
  const squares = numbers.map(number => number * number);

  console.log(squares);
  // Output: [1, 4, 9, 16, 25]
</script>

Example 2:

<script>
  const people = [
    { firstName: 'John', lastName: 'Doe' },
    { firstName: 'Jane', lastName: 'Smith' },
    { firstName: 'Sam', lastName: 'Adams' }
  ];

  const fullNames = people.map(person => `${person.firstName} ${person.lastName}`);

  console.log(fullNames);
  // Output: ["John Doe", "Jane Smith", "Sam Adams"]
</script>

Siva P SV

Siva P SV

I am developer and blogger. I am experienced in PHP, .NET, Android, Ionic, I know these kind of language. Because, I would like to learn new things in this world. I am still learning much more things. Oh, I forgot to mention that I am also one of the Co-Founders of Tuty Rocks