AnyCompiler

Array Methods: map, filter, and reduce

map() and filter() are the two array methods you'll reach for constantly — most Python developers use list comprehensions for exactly this kind of transformation, and these are JavaScript's equivalent.

const numbers = [1, 2, 3, 4, 5];
const squared = numbers.map((x) => x * x);
console.log(squared);

const evens = numbers.filter((x) => x % 2 === 0);
console.log(evens);
Output
[ 1, 4, 9, 16, 25 ]
[ 2, 4 ]

map() transforms every item and returns a new array of the same length. filter() keeps only the items where the function returns true, so the result can be shorter than the original. Neither one changes the original array.

reduce — combining every item into one value

const numbers = [1, 2, 3, 4, 5];
const total = numbers.reduce((sum, x) => sum + x, 0);
console.log(total);
Output
15

reduce() walks through the array, carrying an accumulator (sum) forward from one item to the next. The 0 is the accumulator's starting value. Here it's just adding everything up, but reduce() can build any single result — a total, a maximum, or even a whole new object — out of an array.

Next: exception handling — dealing with errors gracefully instead of letting your program crash.

Practice exercise

Use .map() to build an array of the cubes of the numbers 1 through 4, then print it.