Lesson 11 of 15

Array.map

Array.map

map transforms every element of an array and returns a new array:

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled);  // [2, 4, 6, 8, 10]

The original array is unchanged — map creates a new array and never mutates the input. This immutability makes your code easier to reason about and avoids accidental side-effects. map always returns an array of the same length.

How it Works

map calls the function you provide once for each element, passing:

  1. The element's value
  2. Its index (optional)
  3. The whole array (optional)
const words = ["hello", "world"];
const lengths = words.map(w => w.length);
console.log(lengths);  // [5, 5]

Your Task

Write function squareAll(numbers) that takes an array of numbers and returns a new array where each number is squared.

Use .map() and print the result with .join(", ").

JavaScript loading...
Loading...
Click "Run" to execute your code.