EarniculumGet early accessJoin
← All free samplesFREE SAMPLE LESSON

Working with Data in JavaScript · Arrays and the methods that replace loops

Thinking in transformations

Most loops you write are one of four shapes. Naming them makes code shorter and clearer.

beginnerEnglish15 minArticle

Once you are comfortable with loops, most of the ones you write turn out to be the same four shapes:

  1. Change every item into something else. Prices to prices with tax.
  2. Keep some items. Orders that are unpaid.
  3. Reduce many items to one value. A total, a count, a maximum.
  4. Find one item. The user with this id.

JavaScript has a method for each, and using them says what you meant rather than how you did it.

```

// The loop

const names = [];

for (const user of users) {

names.push(user.name);

}

// The transformation

const names = users.map((user) => user.name);

```

The second version is shorter, but the real gain is that map announces "same number of items, each changed". A reader knows that before reading the body.

The four

ShapeMethodReturns
Change eachmapA new array, same length
Keep somefilterA new array, shorter or equal
Combine to onereduceAny single value
Find onefindThe item, or undefined

Plus two that answer yes or no: some (is any true?) and every (are all true?).

They do not change the original

map and filter return new arrays and leave the input alone. That matters more than it sounds: functions that do not modify their inputs are much easier to reason about, because calling one cannot break something elsewhere.

```

const prices = [10, 20];

const withTax = prices.map((p) => p * 1.2);

// prices is still [10, 20]

```

Chaining

Because each returns an array, they compose:

```

const total = orders

.filter((order) => !order.refunded)

.map((order) => order.amount)

.reduce((sum, amount) => sum + amount, 0);

```

That reads as a sentence: drop the refunds, take the amounts, add them up.

END OF FREE SAMPLE

That lesson is yours to use.

Reading this sample did not enroll you, save progress, or issue a certificate. No reward was earned. Continue with the full course for the remaining lessons and assessments.

Join the waitlist Review the full course