Array Methods

Chaining Array Methods

🙋 Need help? Ask an expert now!

Chaining is a pattern for calling/invoking methods in functional programming. Each method in the chain returns an object that is then used with another method and so on. Chaining methods is essentially calling methods one after another in one statement. As most of the array methods return an array, the methods can be chained and used consecutively to make your code more concise.

The console.log() statement above shows an example of chaining array methods by calling the map() method right after calling the filter() method. As mentioned in the comments above, the filter() method returns a new array [2,4,6,8,10]. This array is then passed to the map() method, where each element is squared. The map() method also returns an array, which is then printed on the console.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [5, 25, 125, 625, 3125, 15625];
            function isOdd(number) {
              return number % 2 == 1;
            }
            function divide(number) {
              return number / 25;
            }
            console.log(arr.filter(isOdd).map(divide));
            

What will the following code segment print to the console?