JavaScript Array Map Method: A Beginner’s Guide

Ashutosh K Singh
2 min readJan 26, 2023
Photo by Max Duzij on Unsplash

JavaScript arrays are a powerful tool for storing and manipulating data in your web applications. One of the most useful built-in methods for working with arrays is the map method. This method allows you to iterate over an array, apply a function to each element, and return a new array with the results.

The basic syntax for the map method is as follows:

array.map(function(element, index, array) {
// code to be executed
});

The function passed to the map method takes three arguments:

  • element: The current element being processed in the array
  • index: The index of the current element in the array
  • array: The original array being processed

In the body of the function, you can perform any calculations or transformations on the element, and then return the result. The map method will then take the returned values and create a new array with them.

Here’s an example of using the map method to square each element in an array:

var numbers = [1, 2, 3, 4, 5];
var squared = numbers.map(function(element) {
return element * element;
});
console.log(squared); // [1, 4, 9, 16, 25]

--

--

No responses yet