Quick Answer

Transform arrays using the map method.

Understanding the Issue

The map() method creates a new array by calling a provided function on every element. It doesn't mutate the original array and is ideal for transforming data without side effects.

The Problem

This code demonstrates the issue:

Javascript Error
const numbers = [1, 2, 3];
// Need to double each number

The Solution

Here's the corrected code:

Javascript Fixed
// Basic map usage
const doubled = numbers.map(n => n * 2);

// With index parameter
const withIndex = numbers.map((n, i) => n * i);

// Mapping objects
const users = [{name: 'Alice'}, {name: 'Bob'}];
const names = users.map(user => user.name);

// Chaining with other methods
const evenSquares = numbers
    .filter(n => n % 2 === 0)
    .map(n => n ** 2);

Key Takeaways

Use map for pure transformations of array elements.