Thursday, September 4, 2025
HomeLanguagesJavascriptLodash _.ternary() Method

Lodash _.ternary() Method

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.

The _.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 takes a single parameter as listed above and discussed 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 Lodash contrib library to be installed. The lodash-contrib library can be installed using npm install lodash-contrib –save

Example 1:

Javascript




// Defining lodash contrib variable
var _ = require('lodash-contrib'); 
  
// Function to be used
function fun() {
    return arguments;
}
  
// Making the ternary function
var gfgFunc = _.ternary(fun);
  
console.log("Arguments are :",
    gfgFunc("first", "second", "third"));


Output:

Arguments are : [Arguments] 
  { '0': 'first', '1': 'second', '2': 'third' }

Example 2:

Javascript




// Defining lodash contrib variable
var _ = require('lodash-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("a", "b", "c", "d", "e", "f"));


Output: 

Arguments are : [Arguments] { '0': 'a', '1': 'b', '2': 'c' }

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

Javascript




// Defining lodash contrib variable
var _ = require('lodash-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(100, 100, 1000, 4, 5, 6, 7));


Output: 

Sum of first 3 arguments is : 1200
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
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6628 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11858 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS