map() Methods in JavaScript

JavaScript2 min read
map() Methods in JavaScript
javascriptmap methodarray methods

The map() method in JavaScript is used to iterate over each element of an array and create a new array with the results of applying a callback function to each element.

map() Methods in JavaScript

The map() method in JavaScript is used to iterate over each element of an array and create a new array with the results of applying a callback function to each element. Unlike forEach(), map() returns a new array and does not modify the original array.

  • The callback function passed to map() can take up to three parameters:
    1. currentValue: The current element being processed (required).
    2. index: The index of the current element (optional).
    3. array: The original array (optional).

Example:

  • We have a products array with each product having a name and price:
const products = [ { name: 'Laptop', price: 1200 }, { name: 'Mobile Phone', price: 900 }, { name: 'Headphone', price: 3000 } ];
  • To show all products and their prices, we use the forEach() method:
products.forEach(item => { document.write(`Name: ${item.name} | Price: ${item.price} <br>`); }); // Output: Name: Laptop | Price: 1200 Name: Mobile Phone | Price: 900 Name: Headphone | Price: 3000

Modifying Product Prices Using map()

  • Now, let's increase the price of each product by 100 without modifying the original products array. We can use the map() method to create a new array with updated prices:
const modifiedProducts = products.map(item => ({ name: item.name, price: item.price + 100 }));
  • Here, the map() method creates a new array modifiedProducts by adding 100 to each product's price.

Displaying the Modified Products:

modifiedProducts.forEach(item => { document.write(`Name: ${item.name} | Price: ${item.price} <br>`); }); // Output: Name: Laptop | Price: 1300 Name: Mobile Phone | Price: 1000 Name: Headphone | Price: 3100
  • The original products array remains unchanged, while the new modifiedProducts array reflects the updated prices.

Summary:

  • The map() method creates a new array by applying a callback function to each element of the original array.
  • It does not modify the original array, making it a non-mutating method.
  • map() is useful when you want to transform an array without affecting the original data.