Arrays

Course 1 · Ch 6
Arrays: Creation, Indexing, and Core Methods
Storing ordered collections of values, and the four methods that do most of the real work: forEach, map, filter, reduce

Chapter 5 established that functions are values that can be passed around. This chapter puts that fact to immediate use: JavaScript arrays come with built-in methods that take a function as an argument and run it against every element. Mastering these four methods replaces almost all manual loop-writing for everyday array work.

Creating and Indexing Arrays

const fruits = ["apple", "banana", "cherry"]; console.log(fruits[0]); // "apple" — indexing starts at 0 console.log(fruits.length); // 3 console.log(fruits[fruits.length - 1]); // "cherry" — last element

An array is declared with const just like any other value — the array's contents can still change even though the binding itself can't be reassigned, the same rule that applied to objects would apply here too. Square brackets create the array; square brackets with an index read from it.

Adding and Removing Elements

const numbers = [1, 2, 3]; numbers.push(4); // [1, 2, 3, 4] — adds to the end numbers.pop(); // [1, 2, 3] — removes from the end numbers.unshift(0); // [0, 1, 2, 3] — adds to the start numbers.shift(); // [1, 2, 3] — removes from the start

push/pop work at the end of the array and are fast; unshift/shift work at the start and have to renumber every other element, so they're slower on large arrays.

forEach — Run a Function for Every Element

const scores = [72, 88, 91]; scores.forEach(score => { console.log(`Score: ${score}`); }); // Score: 72 // Score: 88 // Score: 91

forEach takes a function and calls it once per element, passing that element in as the argument. It's a direct replacement for a for loop (Chapter 4) when the only goal is "do something with each item" — it doesn't build a new array or return a useful value.

map — Transform Every Element Into a New Array

const prices = [10, 20, 30]; const withTax = prices.map(price => price * 1.2); console.log(withTax); // [12, 24, 36] console.log(prices); // [10, 20, 30] — original array is untouched

map runs a function against every element and collects the return values into a brand-new array, leaving the original unchanged. Use map whenever the goal is "the same number of items, but transformed" — converting, scaling, formatting, and so on.

filter — Keep Only the Elements That Pass a Test

const ages = [15, 22, 17, 30]; const adults = ages.filter(age => age >= 18); console.log(adults); // [22, 30]

filter runs a function that returns true or false for each element, and keeps only the elements where it returned true. The result is a new, possibly shorter, array — the original is left alone, same as map.

reduce — Combine Every Element Into a Single Value

const cart = [9.99, 14.50, 3.25]; const total = cart.reduce((runningTotal, price) => runningTotal + price, 0); console.log(total); // 27.74

reduce is the least intuitive of the four, and the most powerful. Its function takes two arguments — the running result so far (accumulator) and the current element — and returns the new running result. The 0 after the function is the starting value for the accumulator, used before any element has been processed.

Forgetting the starting value changes the result
Without that second argument to reduce, the first array element is used as the starting accumulator instead, and the callback runs one fewer time. For sums starting at 0 this often still works by accident — but it silently breaks for anything where the first element isn't a safe starting point (string concatenation, building an object, etc.). Always pass the starting value explicitly.

Chaining Methods Together

const orders = [5, 12, 8, 20, 3]; const totalOfLargeOrders = orders .filter(qty => qty > 5) .map(qty => qty * 2) .reduce((sum, qty) => sum + qty, 0); console.log(totalOfLargeOrders); // 80

Because filter and map each return a new array, their results can be chained directly into the next method call. This reads almost like a sentence: "filter for orders over 5, double each one, then sum them up" — and is the idiomatic JavaScript style for this kind of data processing.

MethodReturnsUse it when...
forEachundefinedYou just need to do something with each item (e.g. log it)
mapNew array, same lengthYou need a transformed version of every element
filterNew array, same or shorterYou need only the elements that match a condition
reduceA single valueYou need to combine everything into one result (sum, total, object)

Coding Challenges

Challenge 1

Given const temps = [18, 22, 15, 30, 27], use map to create a new array converting each Celsius value to Fahrenheit (formula: C * 9/5 + 32). console.log() both the original array and the new one, confirming the original is unchanged.

📄 View solution
Challenge 2

Given const words = ["cat", "elephant", "dog", "hippopotamus", "ant"], use filter to create a new array containing only the words with more than 3 letters. console.log() the result.

📄 View solution
Challenge 3

Given const cart = [{ name: "Book", price: 12 }, { name: "Pen", price: 2 }, { name: "Bag", price: 25 }], use reduce to calculate the total price of all items. Then chain filter and reduce together to calculate the total price of only items costing more than 5.

📄 View solution

Chapter 6 Quick Reference

  • Indexing: arrays start at index 0; array.length gives the count
  • push/pop — add/remove at the end (fast); unshift/shift — add/remove at the start (slower)
  • forEach — run a function per element, returns nothing
  • map — transform every element, returns a new array of the same length
  • filter — keep elements passing a test, returns a new (possibly shorter) array
  • reduce — combine all elements into a single value; always pass a starting value
  • map/filter/reduce never mutate the original array — they return new data
  • Methods can be chained — filter().map().reduce() reads like a processing pipeline
  • Next chapter: objects — properties, methods, and the dot/bracket access patterns