Introduction to map
You'll learn how to use map() to transform every element in an array into something new without changing the original.
What Is map()?
The map() method creates a brand new array by applying a transformation function to each element of the original array. Unlike forEach() (which just loops and returns undefined), map() always returns a new array with the same number of elements as the original.
Think of it like a factory assembly line: every item goes in, gets transformed, and comes out the other side. If you feed in 5 items, you get exactly 5 transformed items back.
How map() Works
You call map() on an array and pass it a function. That function receives each element, transforms it, and returns the new value:
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6, 8]
console.log(numbers); // [1, 2, 3, 4] - original unchanged!
The callback function gets called once per element. Whatever you return becomes the corresponding element in the new array.
More Examples
const names = ['alice', 'bob', 'charlie'];
const capitalized = names.map(function(name) {
return name.toUpperCase();
});
// ['ALICE', 'BOB', 'CHARLIE']
const prices = [10, 20, 30];
const withTax = prices.map(function(price) {
return price * 1.08;
});
// [10.8, 21.6, 32.4]
Key Takeaway: Use map() when you need to transform each element of an array and collect all the results in a new array of the same length—the original stays untouched.