Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript map()

map transforms every element in an array and returns a new array.

It is perfect for formatting data or converting shapes.

Why We Need It

map makes transformations declarative and readable.

It avoids manual loops and keeps data pipelines clean.

Syntax

array.map((value, index, array) => newValue)

Basic Example

1. Basic map

const nums = [1, 2, 3];
const squared = nums.map((n) => n * n);

console.log(squared);

Transform each number into its square.

Real World Example

2. Format strings

const names = ["ada", "sam"];
const caps = names.map((n) => n.toUpperCase());

console.log(caps);

Create a new array of formatted strings.

Multiple Use Cases

Transform Values

map creates a new array by applying a function to each element.

It never changes the original array.

Same Length Output

map always returns an array of the same length.

If you need fewer items, use filter instead.

Index and Array

The callback receives value, index, and the original array.

Use index when you need position-based logic.

More Examples

3. Use index

const items = ["a", "b"];
const labeled = items.map((item, i) => i + ":" + item);

console.log(labeled);

Use the index parameter when needed.

4. Map objects

const users = [{ id: 1 }, { id: 2 }];
const ids = users.map((u) => u.id);

console.log(ids);

Pick fields from objects into a new array.

Comparison

Without

const out = [];
for (const n of nums) {
  out.push(n * 2);
}

With

const out = nums.map((n) => n * 2);

Common Mistakes and Fixes

Using map for side effects

Use forEach when you are not returning a new array.

Mutating items in map

Return new objects instead of mutating existing ones.

Expecting map to filter

Use filter to remove items.

Interview Questions

What does map return?

A new array with transformed values.

When should you not use map?

When you only need side effects; use forEach.

Does map mutate?

No, map does not mutate the original array.

Practice Problem

Practice: Convert an array of prices to include tax at 18 percent.

const prices = [10, 20, 30];
// TODO: return prices with tax added

One Possible Solution

const prices = [10, 20, 30];
const withTax = prices.map((p) => p * 1.18);
console.log(withTax);

Frequently Asked Questions

Does map change the original array?

No, it returns a new array.

Can map be chained?

Yes, map can be chained with filter, reduce, and more.

What does map return?

A new array with the same length as the original.

Try It Yourself

Try mapping different transformations.