How do you know when you can "chain" methods of functions?

I just tried a simple problem on Codewars to replace numbers in words with letters. The #'s were 5, 0, and 1, and to replace them with S, O, and I. So I did an if / else block using includes() for the condition and replace() for the operation. Well, I didn’t get it so I looked at the answers.

The most common solutions involved chaining .replace 3 times to the string variable. As soon as I saw the answers I understood it but I had no idea you can do that. I’ve seen chaining involving map, filter, sort, etc.

Can you chain any and all methods together, assuming it makes sense? Is there a way to tell when you can chain them or is it something you have to learn through practice?

If anyone is curious, here is the solution

stringCorrect = char => char.replace(/5/g, 'S').replace(/0/g, 'O').replace(/1/g, 'I');

In this case, replace is a method on the string prototype so it can be called on any string, and it also happens to return a string (therefore they have access to replace).

const stringCorrect = char => {
  const first = char.replace(/5/g, 'S');
  const second = first.replace(/0/g, 'O');
  const third = second.replace(/1/g, 'I');
  return third;
}

Is it easier to see what’s going on when written like this?

But basically this comes down to being familiar with the methods available on each of the different prototypes (this will mostly be String and Array for chaining), and knowing their return values.

1 Like

Thanks. Let me read those docs…