Underscore.js _.binary() Method

The Underscore.js _.binary() method returns a new function that accepts only two arguments and passes these arguments to the given function. Additional arguments are discarded.
Syntax:
_.binary( fun )
Parameters: This method takes a single parameter as listed above and discussed below.
- fun: This is the given function.
Return Value: It returns a new function.
Note: To execute the below examples, you have to install the underscore-contrib library by using this command prompt and execute the following command.
npm install underscore-contrib
Example 1:
Javascript
// Defining underscore contrib variable var _ = require('underscore-contrib'); // Function function fun(){ var mul = 1; for (var i = 0; i < arguments.length; i++) { mul = mul * arguments[i]; } return mul; } var gfgFunc = _.binary(fun); console.log("Multiplication is :", gfgFunc(2,3)); |
Output:
Multiplication is : 6
Example 2:
Javascript
// Defining underscore contrib variable var _ = require('underscore-contrib'); // Function function fun() { var mul = 1; for (var i = 0; i < arguments.length; i++) { mul = mul * arguments[i]; } return mul; } var gfgFunc = _.binary(fun); // Only operates for first two parameters console.log("Multiplication is :", gfgFunc(2,23,2,2)); |
Output:
Multiplication is : 46
Example 3:
Javascript
// Defining underscore contrib variable var _ = require('underscore-contrib'); // Function function fun() { return arguments; } var gfgFunc = _.binary(fun); // Only first two parameters will // be used as arguments console.log("Binary Arguments are :", gfgFunc("a", "b", "c", "d", "e")); |
Output:
Binary Arguments are : [Arguments] { '0': 'a', '1': 'b' }
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!


