Calling Methods One After Another
filter, map and toSorted all return a new array, so you can call the next method directly on the result. This is called chaining. Here is a task: take the names with at least four letters, sort them, and print them on one line with commas between them.
const names = ["Emma", "Bob", "Alice", "Dave", "Carol"];
const result = names
.filter(n => n.length >= 4)
.toSorted()
.join(", ");
console.log(result);
Output:
Alice, Carol, Dave, Emma
Read the chain from top to bottom and it matches the task: keep the long names, sort them, join them. Each step works on the result of the step above it.
You can write each step on its own line, starting with the dot. JavaScript reads it as one long expression until the semicolon. With one step per line, a reader can see the whole recipe by looking down the left side.
join is the new method here. It glues all the elements into one string and puts your separator between them. The separator goes only between elements, never after the last one:
const fruits = ["fig", "kiwi", "plum"];
console.log(fruits.join(", "));
console.log(fruits.join("-"));
console.log(fruits.join(""));
Output:
fig, kiwi, plum
fig-kiwi-plum
figkiwiplum
join turns an array into a string, so it is often the last step of a chain. It is the opposite of split, which turns a string into an array.
A chain does not have to end with an array. If the last step is reduce or find, the result is a single value. This chain doubles the prices of 8 or more and adds them up:
const prices = [12, 5, 30, 8];
const total = prices
.filter(p => p >= 8)
.map(p => p * 2)
.reduce((acc, p) => acc + p, 0);
console.log(total);
Output:
100
Two tips for writing chains. Put filter early, so the later steps have fewer elements to work on. And when a chain gets longer than four or five steps, store a middle result in a variable with a clear name, such as const longNames = .... A good name makes the chain easier to follow.
In the exercise, build one chain: keep the names that are long enough, sort them, and join them with a comma and a space.