Ad space (banner)
🟨JavaScript Lessons
Lesson 24 / 69

Transforming Arrays with map

In this lesson you'll master array's .map() method so you can build a new array by transforming each element of an existing one. This is for people searching "JavaScript map usage" or "JavaScript array transformation."

.map(function) applies the same processing to every element of an array and produces a new array. It's like "a machine that processes every item the same way as it passes over a conveyor belt." The original array doesn't change. This is one of the most frequently used array methods in real web apps, for things like formatting a list of data for display.

The sample code creates a new array, doubled, that doubles each element of the nums array, using .map((n) => n * 2). Check the console output to confirm that the original nums array is left unchanged. It's shorter than writing it one element at a time in a for loop, and it also conveys "what you're trying to do" more clearly.

A common beginner stumbling block is that the callback function passed to .map() must always return a value. Forgetting the return makes every element of the new array undefined. It's also easy to confuse with .forEach(), but a key difference is that forEach doesn't produce a new array.

In real development, map is used constantly for processing like converting an array of product data received from a server into an array of HTML elements for display. The safety of being able to build a new array without breaking the original one is another reason it's favored in real projects.

.map() is also easy to chain — combining .filter() to narrow things down and then .map() to transform them is a pattern you'll see frequently in real work too.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)