Thuta Learning
JavaScript
IntermediateProgrammingBeginner

JS Arrays

JavaScriptLesson 1330 min

What you'll walk away with

  • Read items by index and use length to reach the last item
  • Tell apart methods that mutate the original array from methods that return a new one
  • Choose correctly between forEach (side effects) and map (a new array)
  • Select, search and combine data with filter, find, some and reduce
  • Sort a number array correctly with a comparator

Explain it simply

Explain it simply

Picture a shelf in a pharmacy. The slots are numbered 0, 1, 2 and so on, and each slot holds one item. Saying "bring me the item in slot 2" finds it instantly, and you can always place a new item at the end of the shelf.

A JavaScript array is that shelf. It stores items such as ["Banana", "Orange", "Apple"] in order inside one variable, and you read them by index, as in fruits[0]. Methods such as push, map and filter add, transform and select items without you writing the loop yourself.

Problem → Why → Solution

The problem: sort() orders prices wrongly and changes the original

A "cheapest first" list is needed, so the code calls sort(). In the result, 100 sits in front of 9. Stranger still, the original prices array, which another part of the page shows in the order items were added, has changed as well.

prices.js
const prices = [10, 9, 100, 1];

const cheapestFirst = prices.sort();
console.log(cheapestFirst); // [ 1, 10, 100, 9 ]  wrong order
console.log(prices);        // [ 1, 10, 100, 9 ]  the original changed too

Why does this happen?

Without a comparator, sort() converts items to strings and orders them like words in a dictionary: "100" comes before "9" because "1" sorts before "9". On top of that, sort() does not build a new array; it rearranges the original in place and returns that same array, so cheapestFirst and prices are one array. prices.toSorted((a, b) => a - b), or [...prices].sort((a, b) => a - b), fixes both problems.

Core concept: indexes, mutation and callback methods

An array is an ordered, zero-indexed collection. The first item is arr[0] and the last is arr[arr.length - 1], or arr.at(-1). Reading an index that does not exist gives undefined rather than an error. Arrays are a kind of object, so the reference rules from the objects lesson apply: a const array's items can still change, and const b = a; does not create a new array.

Sort array methods into two groups. The first group mutates the original array directly. The second leaves the original alone and returns a new array or value. Using a method without knowing its group leads to bugs like the one in the problem section.

MethodMutates?Returns
push / popYesnew length / removed item
splice / sort / reverseYesremoved items / the same array
map / filter / slice / concatNoa new array
find / some / every / reduceNoan item, a boolean or one value

Methods such as map, filter and forEach call a callback function once per item and pass it (item, index, array). map builds a new array of the same length from the callback's return values, and filter keeps only the items for which the callback returns true. forEach builds nothing and returns undefined, so use it only for side effects such as printing. find returns the first matching item, or undefined, and some and every return a boolean. reduce combines all items into one value, such as a total; always give it an initial value.

When sorting numbers, always pass a comparator such as (a, b) => a - b. A negative result puts a first and a positive result puts b first. To keep the original untouched, use toSorted(), available in Node 20+ and current browsers.

Mental model: edit in place, or make new?
  1. Before calling a method, ask:
  2. Does it edit in place? (push, sort)
  3. Or return new? (map, filter)
  4. Store new results in a new variable

When other code shares the array, prefer the methods that return a new array.

General pattern

javascript
const list = [itemA, itemB, itemC];

list[index];                 // read one item
list.push(newItem);          // add to the end (mutates)

const changed = list.map(function (item) {
  return transform(item);    // new array, same length
});
const kept = list.filter(function (item) {
  return condition(item);    // new array, matching items only
});

These are the four basic shapes: read by index, add to the end with push, transform every item with map, and select items with filter. The callbacks for map and filter must return a value.

Example: add to, loop over and transform a fruits array

The code adds an item to fruits with push and prints each item with forEach. It then builds a new upper-case array with map and checks that the original array was not changed by it.

fruits.js
const fruits = ["Banana", "Orange", "Apple"];

// Add a new item to the end
fruits.push("Mango");

// Loop through the array
fruits.forEach(function(fruit) {
  console.log("I like " + fruit);
});

const loud = fruits.map(function(fruit) {
  return fruit.toUpperCase();
});
console.log(loud);
console.log(fruits.length + " fruits, first is " + fruits[0]);

Code breakdown

  1. Line 4fruits.push("Mango");

    push adds an item to the end of the original array; it mutates. That is allowed even though fruits is const, because the variable is not being reassigned.

  2. Lines 7-9fruits.forEach(function(fruit) {

    forEach calls the callback once per item, passing the current item as fruit. Printing is a side effect, which is exactly what forEach is for.

  3. Lines 11-13return fruit.toUpperCase();

    map builds a new array from whatever the callback returns. Forget the return and loud becomes [undefined, undefined, ...].

  4. Line 15console.log(fruits.length + " fruits, first is " + fruits[0]);

    length is 4 because of push, and fruits[0] is still "Banana" in its original case: map did not touch the original.

You should see
I like Banana
I like Orange
I like Apple
I like Mango
[ 'BANANA', 'ORANGE', 'APPLE', 'MANGO' ]
4 fruits, first is Banana

Search, test and combine: find, some, every, reduce

Run each method on a score array. find returns only the first matching item, while filter returns every match as an array. The second argument to reduce, 0, is its initial value, so an empty array returns 0 instead of throwing a TypeError. The last lines sort with a comparator through toSorted and show the original is unchanged.

scores.js
const scores = [72, 95, 58, 88];

const firstFail = scores.find(function (s) { return s < 60; });
const passed = scores.filter(function (s) { return s >= 60; });
const anyPerfect = scores.some(function (s) { return s === 100; });
const allPositive = scores.every(function (s) { return s > 0; });
const total = scores.reduce(function (sum, s) { return sum + s; }, 0);
const emptyTotal = [].reduce(function (sum, s) { return sum + s; }, 0);

console.log(firstFail, passed, anyPerfect, allPositive, total, emptyTotal);
console.log(scores.toSorted(function (a, b) { return a - b; }));
console.log(scores); // still in the original order

In real projects

Where arrays show up in real projects

A shop's product list page is a good example of array methods working in sequence. Once the API returns an array of product objects, filter keeps the ones in stock, map turns them into display text such as "Notebook - $2.50", and reduce totals the cart. The search box relies on includes or filter, and the "sort by price" button sorts with a comparator.

The key is never to mutate the original array from the API, because when the user clears a filter, every product has to come back. Most projects therefore prefer methods that return a new array, like filter, map and toSorted, and their tests assert that the source array keeps its length and order afterwards. UI libraries such as React also need a new array, since they cannot detect a change made to a state array with push.

Common mistakes

Common mistakes

1. Sorting numbers without a comparator

[10, 9, 100, 1].sort() returns [1, 10, 100, 9] and rearranges the original. Always pass (a, b) => a - b for numbers, and use toSorted() when you still need the original.

2. Expecting a result from forEach

After const doubled = nums.forEach(function (n) { return n * 2; });, doubled is undefined, because forEach throws away the callback's return values. Use map when you want a new array.

3. reduce with no initial value on an empty array

[].reduce(function (a, b) { return a + b; }) throws the TypeError "Reduce of empty array with no initial value". A filter step can easily leave an array empty, so always pass an initial value: reduce(..., 0).

Best practices

Best practices

  • Give array variables plural names such as products or scores, and their callback parameters singular names such as product or score.
  • Split a filter, map, reduce chain into steps and store each step's result in a named variable, which makes debugging easier.
  • When you need just one item, use find instead of filter(...)[0]; it stops at the first match.

Mini challenge

Mini challenge: an in-stock product catalog

Write buildCatalog(), which takes an array of product objects, keeps those in stock, turns them into display labels, totals their prices, and leaves the source array unchanged.

  • Use filter to keep only products with stock > 0
  • Use map to build labels like "Name - $2.50"
  • Use reduce with an initial value of 0 to total one of each selected product
  • Use find for the first in-stock product under $2 and some to check whether anything is sold out
  • Finally print that the source array still holds 4 products
catalog.js
const products = [
  { name: "Notebook", price: 2.5, stock: 12 },
  { name: "Pen", price: 0.8, stock: 0 },
  { name: "Backpack", price: 24, stock: 3 },
  { name: "Ruler", price: 1.2, stock: 5 },
];

function buildCatalog(list) {
  // TODO: available = only products with stock > 0 (filter)
  // TODO: labels = "Name - $price" with 2 decimals (map)
  // TODO: total = sum of available prices, starting from 0 (reduce)
  // TODO: return { labels, total }
}

// TODO: print the labels and the total
// TODO: find the first in-stock product under $2; check if any product is sold out
// TODO: print how many products the source array still has

Expected: [ 'Notebook - $2.50', 'Backpack - $24.00', 'Ruler - $1.20' ] Total of one each: $27.70 Cheap pick: Ruler Any sold out? true Source still has 4 products

Show hint

Inside map, p.price.toFixed(2) turns 2.5 into "2.50". The find callback needs both conditions: p.stock > 0 && p.price < 2.

Show solution
catalog.js
const products = [
  { name: "Notebook", price: 2.5, stock: 12 },
  { name: "Pen", price: 0.8, stock: 0 },
  { name: "Backpack", price: 24, stock: 3 },
  { name: "Ruler", price: 1.2, stock: 5 },
];

function buildCatalog(list) {
  const available = list.filter(function (p) {
    return p.stock > 0;
  });
  const labels = available.map(function (p) {
    return p.name + " - $" + p.price.toFixed(2);
  });
  const total = available.reduce(function (sum, p) {
    return sum + p.price;
  }, 0);
  return { labels, total };
}

const catalog = buildCatalog(products);
console.log(catalog.labels);
console.log("Total of one each: $" + catalog.total.toFixed(2));

const cheap = products.find(function (p) {
  return p.stock > 0 && p.price < 2;
});
const anySoldOut = products.some(function (p) {
  return p.stock === 0;
});
console.log("Cheap pick: " + cheap.name);
console.log("Any sold out? " + anySoldOut);
console.log("Source still has " + products.length + " products");

Quick quiz 1 / 3

What does console.log([10, 9, 100, 1].sort()); print?

Quick quiz 2 / 3

What does const r = [1, 2, 3].forEach(function (n) { return n * 2; }); console.log(r); print?

Quick quiz 3 / 3

Which method returns a new array and leaves the original unchanged?

What to remember

  • An array is an ordered collection indexed from 0; the last item is arr[arr.length - 1].
  • push, pop, splice, sort and reverse mutate; map, filter, slice and concat return a new array.
  • forEach is for side effects and returns undefined; use map when you want a transformed array.
  • find, some, every and reduce search, test and combine; always give reduce an initial value.
  • Sort numbers with the comparator (a, b) => a - b, and use toSorted() to keep the original.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

JS Arrays | Thuta Learning