Open In App

Lodash _.once() Method

Last Updated : 03 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Lodash _.once() method of Function in lodash is used to create a function that calls the func parameter of this method only once. However, repeated calls to this function will return the value returned in the first call. 

Note:

The function 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 that is to be restricted.

Return Value:

  • This method returns the new restricted function.

Example 1: In this example, the hold is called multiple times but only the value of the first call is returned as you can call func only once as stated above.

JavaScript
// Requiring lodash library
const _ = require('lodash');

// Calling once() method with its parameter
let 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!

Example 2: In this example, each time the fetch is called the same value is returned as returned to the first call.

JavaScript
// Requiring lodash library
const _ = require('lodash');

// Calling once() method with its parameter
let fetch = _.once(function (value) {
    return value;
});

// Calling fetch multiple times
console.log(fetch(1013));
console.log(fetch(1014));

Output:

1013
1013

Similar Reads