Skip to content
Related Articles

Related Articles

Improve Article

Underscore.js _.tap() Function

  • Last Updated : 14 Oct, 2020
Geek Week

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:

  • object: It is the object stated.
  • interceptor: It is the function to be called.

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

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :