map() Methods in JavaScript
•JavaScript•2 min read

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:
- currentValue: The current element being processed (required).
- index: The index of the current element (optional).
- array: The original array (optional).
Example:
- We have a
productsarray with each product having anameandprice:
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: 3000Modifying Product Prices Using map()
- Now, let's increase the price of each product by 100 without modifying the original
productsarray. We can use themap()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 arraymodifiedProductsby 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
productsarray remains unchanged, while the newmodifiedProductsarray 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.


