Sub topic 1
Functions That Take Functions: Callbacks in Array Methods
Prerequisites
This chapter assumes you can declare variables, arrays, and objects. You should also be able to write regular and arrow functions and read a basic for loop.
Callbacks in Array Methods
A higher-order function is a function that takes another function as an argument or returns one. map and filter are higher-order functions. You pass them a callback, which is a function they call for you, once per element. The method handles the looping, and your callback handles one element at a time.
Returning New Arrays Instead of Mutating
map and filter build and return a new array, and the original stays as it was. That makes your code easier to follow, because a variable keeps its contents after you pass it through a transformation. A common error is mutating shared objects inside the callback. The new array then holds the same object references as the original:
const users = [{ name: 'Ada', active: false }];
const activated = users.map(u => ({ ...u, active: true }));
console.log(users[0].active); // false
console.log(activated[0].active); // trueThe spread copy { ...u } keeps the original object unchanged.
What Your Callback Receives: Element, Index, and Array
Each call gets three arguments: the element, its index, and the whole array. Most callbacks use only the first one. The extra arguments cause bugs when you pass a function that accepts more than one parameter:
console.log(['1', '2', '3'].map(parseInt)); // [1, NaN, NaN]
console.log(['1', '2', '3'].map(s => parseInt(s, 10))); // [1, 2, 3]parseInt reads the index as its radix (the number base). A radix of 0 means "use the default base", so '1' parses correctly. Radix 1 is invalid, and '3' is not a valid digit in base 2, so both give NaN.
map: Transforming Every Element
map returns an array of the same length. Each slot holds whatever your callback returned for that element.
const names = ['ada', 'grace', 'linus'];
const capitalized = names.map(name => name[0].toUpperCase() + name.slice(1));
console.log(capitalized); // ['Ada', 'Grace', 'Linus']
console.log(names); // ['ada', 'grace', 'linus']filter: Keeping Only What Matches
filter takes a predicate, which is a callback that returns true or false. It keeps each element for which the predicate returns a truthy value, so the result can be shorter than the input.
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]Exercise
What does [10, 15, 20].filter((n, i) => i > 0).map(n => n / 5) return, and is the original array changed?
Show answer
[3, 4]. filter keeps the elements at index 1 and 2, which are 15 and 20, and map divides each by 5. The original array stays [10, 15, 20].