ShaharAmir
← Back to Blog
JavaScript2 min read

Array.map() Explained

Learn how to transform arrays in JavaScript with the map method

S
Shahar Amir

Array.map() Explained

The map() method is one of the most useful array methods in JavaScript. It creates a new array by transforming every element in the original array.

Basic Syntax

javascript
123
const newArray = array.map((element, index, array) => {
// return transformed element
});

Simple Example

Let's say you have an array of prices and want to apply a 10% discount:

javascript
12345
const prices = [10, 20, 30];
const discounted = prices.map(price => price * 0.9);
console.log(discounted);
// [9, 18, 27]

With Objects

map() is especially powerful when working with arrays of objects:

javascript
123456789101112
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
];
const names = users.map(user => user.name);
// ['John', 'Jane']
const formatted = users.map(user => ({
...user,
displayName: `${user.name} (${user.age})`
}));

Key Points

  • Returns a new array - doesn't modify the original
  • Same length - output array has same length as input
  • Transform, don't filter - use filter() to remove items

When NOT to Use map()

If you don't need the returned array, use forEach() instead:

javascript
12345
// ❌ Don't do this
array.map(item => console.log(item));
// ✅ Do this instead
array.forEach(item => console.log(item));

That's it! map() is simple but incredibly powerful. Use it whenever you need to transform every item in an array.

#arrays#javascript#fundamentals

Stay Updated 📬

Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.