Saturday, December 13, 2025
HomeLanguagesJavascriptUnderscore.js _.ternary() Method

Underscore.js _.ternary() Method

The Underscore.js _.ternary() method returns a new function that accepts only three arguments and passes these arguments to the given function. Any additional arguments that are given are discarded.

Syntax:

_.ternary( fun )

Parameters: This method accepts a single parameter as mentioned above and described below:

  • fun: This is the function that should be used for the parameters.

Return Value: This method returns a new function.

Note: This method will not work in normal JavaScript because it requires the underscore-contrib library to be installed. It can be installed using npm install underscore-contrib

Example 1:

Javascript




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Function to be used
function fun() {
    return arguments;
}
  
// Making ternary function
var gfgFunc = _.ternary(fun);
  
console.log("Arguments are :",
    gfgFunc(1, 2, 3));


Output:

Arguments are : [Arguments] { '0': 1, '1': 2, '2': 3 }

Example 2:

Javascript




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Function to be used
function fun() {
    return arguments;
}
  
// Making the ternary function
var gfgFunc = _.ternary(fun);
  
// Arguments more than 3 are excluded
console.log("Arguments are :",
    gfgFunc(1, 2, 3, 4, 5, 6, 7, 8));


Output: 

Arguments are : [Arguments] { '0': 1, '1': 2, '2': 3 }

Example 3: In this example, we will add arguments but only the first 3 arguments will be using this method.

Javascript




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
// Function to be used
function add() {
    s=0;
    for (i=0; i<3; i++) {
        s+=arguments[i];
    }
    return s;
}
  
// Making the ternary function
var gfgFunc = _.ternary(add);
  
// Arguments more than 3 are excluded
console.log("Sum of first 3 arguments is :",
    gfgFunc(1, 2, 3, 4, 5, 6, 7));


Output: 

Sum of first 3 arguments is : 6
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen 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!
RELATED ARTICLES

Most Popular

Dominic
32446 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6814 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12030 POSTS0 COMMENTS
Shaida Kate Naidoo
6949 POSTS0 COMMENTS
Ted Musemwa
7200 POSTS0 COMMENTS
Thapelo Manthata
6897 POSTS0 COMMENTS
Umr Jansen
6882 POSTS0 COMMENTS