map() Methods in JavaScript

JavaScript
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 array with each product having a and :
1const products = [
2    { name: 'Laptop', price: 1200 },
3    { name: 'Mobile Phone', price: 900 },
4    { name: 'Headphone', price: 3000 }
5];
  • To show all products and their prices, we use the method:
1products.forEach(item => {
2    document.write(`Name: ${item.name} | Price: ${item.price} <br>`);
3});
4
5
6
7// Output:
8Name: Laptop | Price: 1200
9Name: Mobile Phone | Price: 900
10Name: Headphone | Price: 3000

Modifying Product Prices Using map()

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

Displaying the Modified Products:

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

Summary:

  • The 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.
  • is useful when you want to transform an array without affecting the original data.