Course contentsShow
← JavaScript
Lesson 440 of 2,72312. Higher-Order FunctionsFree lesson

Array.prototype.map: The Basics

How map transforms each element of an array by applying a function, returning a new array.

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:

  1. map takes your function as an argument
  2. It calls your function once for each element
  3. Your function receives the current element as a parameter
  4. 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.