Course contentsShow
← JavaScript
Lesson 910 of 2,72320. Array Iteration and TransformationFree lesson

Updating Elements with .map()

Replace specific elements conditionally using map to produce a new array with changes.

Updating Elements with .map()

You'll learn how to replace or modify specific array elements conditionally using .map() while keeping your original array untouched.

The Core Idea

When you need to update certain elements in an array based on a condition, .map() is your immutable solution. Unlike direct index assignment (array[i] = newValue), which mutates the original array, .map() creates a brand new array where you can conditionally transform elements while leaving others unchanged.

Think of it like photocopying a document and marking changes on the copy—your original stays pristine while you produce an updated version.

How It Works

The pattern is simple: inside .map()'s callback, use a conditional to decide whether to return a modified value or the original element:

const prices = [10, 25, 15, 30];

// Apply a 10% discount to items over $20
const discounted = prices.map(price => {
  if (price > 20) {
    return price * 0.9;  // 10% off
  }
  return price;  // keep original
});

console.log(discounted);  // [10, 22.5, 15, 27]
console.log(prices);      // [10, 25, 15, 30] — unchanged!

You can also use ternary operators for concise conditional updates:

const statuses = ['active', 'inactive', 'pending', 'active'];

// Change 'inactive' to 'disabled'
const updated = statuses.map(status => 
  status === 'inactive' ? 'disabled' : status
);

console.log(updated);  // ['active', 'disabled', 'pending', 'active']

Why This Matters

This approach gives you fine-grained control—update only what needs updating while preserving everything else, all without side effects.

Key Takeaway: Use .map() with conditionals to selectively update array elements immutably—return the transformed value when your condition matches, otherwise return the original element.