Array.prototype.map: The Basics
What you'll learn: How to use map to transform every element in an array into a new array.
What Is map?
map is a higher-order function (a function that takes another function as an argument) built into arrays. It visits each element in your array, applies a transformation function you provide, and collects all the results into a brand new array.
Think of it like a factory assembly line: raw materials (your original array) go in one end, each piece gets transformed by a machine (your function), and finished products (the new array) come out the other end. The original materials remain unchanged.
How map Works
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
Here's what happens:
maptakes your function as an argument- It calls your function once for each element
- Your function receives the current element as a parameter
- Whatever your function returns becomes the corresponding element in the new array
Why This Matters
Instead of manually looping and building a new array yourself, map does the heavy lifting. It's cleaner and expresses your intent: "transform each element."
const names = ['alice', 'bob', 'charlie'];
const capitalized = names.map(function(name) {
return name.toUpperCase();
});
console.log(capitalized); // ['ALICE', 'BOB', 'CHARLIE']
Key Takeaway: map transforms each array element by applying a function, returning a new array of the same length while leaving the original array untouched.