Online Compiler logoOnline Compiler
Array Methods

JavaScript map() Method

Transform array elements and create new arrays with the powerful map() method without modifying the original array.

What is map()?

The map() method creates a new array by calling a function for each element in the original array. It doesn't modify the original array and always returns a new array with the same length.

Basic Example: Double Array Values Using map()

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

Use map() to transform each element in an array and return a new array without modifying the original.

Syntax

JavaScript map() Syntax

array.map((element, index, array) => {
  // Return the transformed element
  return newElement;
});

The map() method executes a callback for every element and returns a new array containing the transformed results.

element: The current element being processed

index (optional): The index of the current element

array (optional): The entire array being mapped

Returns: A new array with transformed elements

Common Use Cases

1. Transform Numbers

Transform Numbers with map()

const numbers = [1, 2, 3, 4];
const squared = numbers.map(n => n * n);
console.log(squared); // [1, 4, 9, 16]

map() can perform mathematical operations on array elements and return a new transformed array.

2. Extract Properties from Objects

Extract Object Properties Using map()

const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

const names = users.map(user => user.name);
console.log(names); // ['Alice', 'Bob', 'Charlie']

map() is commonly used to extract specific properties from objects and create a new array.

3. Convert Strings to Numbers

Convert String Array to Numbers

const strings = ['1', '2', '3', '4'];
const numbers = strings.map(Number);
console.log(numbers); // [1, 2, 3, 4]

You can use map() with the Number function to quickly convert string values into numeric values.

4. Using Index Parameter

Using Index in map() Callback

const letters = ['a', 'b', 'c'];
const indexed = letters.map((letter, index) => 
  `${index}: ${letter}`
);
console.log(indexed); // ['0: a', '1: b', '2: c']

The map() callback receives the element and its index, allowing you to generate indexed or formatted results.

5. Create JSX Elements (React)

Render Lists in React Using map()

const items = ['Apple', 'Banana', 'Orange'];
const listItems = items.map((item, index) => (
  <li key={index}>{item}</li>
));

In React, map() is commonly used to render lists of JSX elements from an array of data.

map() vs forEach()

Aspectmap()forEach()
ReturnsNew arrayundefined
Use WhenNeed transformed dataNeed side effects only
ChainableYesNo

Chaining map() with Other Methods

Method Chaining with map(), filter(), and reduce()

const numbers = [1, 2, 3, 4, 5];

// Chain map with filter
const result = numbers
  .map(n => n * 2)        // [2, 4, 6, 8, 10]
  .filter(n => n > 5)     // [6, 8, 10]
  .reduce((a, b) => a + b, 0); // 24

console.log(result); // 24

map() can be chained with other array methods like filter() and reduce() to perform powerful data transformations.

Common Mistakes to Avoid

❌ Forgetting map() Returns a New Array

Mistake: Ignoring map() Return Value

const numbers = [1, 2, 3];
numbers.map(n => n * 2); // Doesn't save result!
console.log(numbers); // [1, 2, 3] - unchanged

// Correct:
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6]

map() returns a new array. If you don't store the result, the transformation will be lost.

❌ Not Returning a Value from Callback

Mistake: Not Returning a Value in map()

const numbers = [1, 2, 3];
const result = numbers.map(n => {
  n * 2; // Forgot return!
});
console.log(result); // [undefined, undefined, undefined]

// Correct:
const result = numbers.map(n => n * 2);
// or
const result = numbers.map(n => {
  return n * 2;
});

The callback function must return a value. Otherwise, the new array will contain undefined.

❌ Using map() for Side Effects Only

Mistake: Using map() for Side Effects

// Don't use map() just for side effects
const numbers = [1, 2, 3];
numbers.map(n => console.log(n)); // Wasteful

// Use forEach() instead:
numbers.forEach(n => console.log(n));

Use forEach() when you only need side effects like logging. map() should be used for data transformation.

Frequently Asked Questions

Does map() modify the original array?

No, map() is non-mutating. It creates and returns a new array while leaving the original untouched.

Can I use map() on strings?

Mapping Characters from a String

const str = 'hello';
const chars = Array.from(str).map(char => char.toUpperCase());
console.log(chars); // ['H', 'E', 'L', 'L', 'O']

Convert a string into an array using Array.from() and apply map() to transform each character.

What's better: map() or a for loop?

map() is more concise and chainable. Use it when you need to transform data. Use loops when you need complex logic or early exit.

Can map() return different types?

Returning Different Data Types with map()

const values = [1, 'two', true];
const mixed = values.map(v => typeof v);
console.log(mixed); // ['number', 'string', 'boolean']

map() can return any type of value, allowing flexible transformations of array elements.

Best Practices

  • Use map() when you need to transform array elements
  • Chain map() with filter() and reduce() for powerful transformations
  • Always return a value from the callback function
  • Use forEach() if you only need side effects, not data transformation
  • Save the result of map() to a variable if you need to use it