Open In App

Underscore.js _.tap() Function

Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invoke, etc even without using any built-in objects.

The _.tap() function is an inbuilt function in Underscore.js library of JavaScript which is used to call interceptor with the stated object. Moreover, the main purpose of this method is to “tap into” a method chain, so that it can perform operations inside the chain on the intermediate results. 



Syntax:

_.tap(object, interceptor)

Parameters: It accepts two parameters which are specified below:



Return Value: This method returns the object.

Example 1:




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <script>
        console.log(_.chain([4, 5, 6, 7])
        .tap(function (array) {
            array.push(8);
        }))
            .value(); 
    </script>
</body>
  
</html>

Output:

[4, 5, 6, 7, 8]

Example 2:




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <script>
        console.log(_.chain(['a', 'b', 'c', 'd'])
        .tap(function (array) {
            array.pop();
        }))
            .value(); 
    </script>
</body>
  
</html>

Output:

["a", "b", "c"]

Example 3:




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <script>
        console.log(_.chain([1, 2, 3, 4, 5, 6, 7, 8, 9])
            .filter(function (number) 
                { return number % 3 == 0; })
            .tap(alert)
            .map(function (number) 
                { return number * number }))
            .value();
    </script>
</body>
  
</html>

Output:

3, 6, 9   // Result of filter function
[9, 36, 81] // After tap method map function is performed

Here, the map function is applied on the intermediate results as obtain by filter method.

Reference: https://underscorejs.org/#tap


Article Tags :