Saturday, January 31, 2026
HomeLanguagesJavascriptLodash _.once() Method

Lodash _.once() 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 _.once() method of Function in lodash is used to create a function which can call func parameter of this method only once. However, repeated calls to this function will return the value returned in the first call. 

Note: The func parameter of this method is called with this binding along with the arguments of the created function.

Syntax:

_.once(func)

Parameters: This method accepts a single parameter which is described below:

  • func: It is the function which is to be restricted.

Return Value: This method returns the new restricted function.

Example 1:

Javascript




// Requiring lodash library
const _ = require('lodash');
  
// Calling once() method with its parameter
var hold = _.once(function(trap){
   console.log(trap + '!');
});
  
// Calling hold multiple times
hold('Logged in to the console');
hold('GfG');
hold('CS');


Output:

Logged in to the console!

Here, hold is called multiple times but only the value of first call is returned as you can call func only once as stated above.

Example 2:

Javascript




// Requiring lodash library
const _ = require('lodash');
  
// Calling once() method with its parameter
var fetch = _.once(function(value){
   return value;
});
  
// Calling fetch multiple times
console.log(fetch(1013));
console.log(fetch(1014));


Output:

1013
1013

Here, each time the fetch is called the same value is returned as returned to the first call.

Reference: https://lodash.com/docs/4.17.15#once

RELATED ARTICLES

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12066 POSTS0 COMMENTS
Shaida Kate Naidoo
6987 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS