Open In App

Underscore.js _.times() Function

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Underscore.js _.times() function is used to call the function a particular number of times i.e. execution of a function(f) “n” times.

NOTE: It is very necessary to link the underscore CDN before going and using the underscore functions in the browser. When linking the underscore.js CDN link, the “_” is attached to the browser as a global variable.

Syntax:

_.times(n, function);

Parameters:

  • n: It tells how many times a function is needed to be executed.
  • function: It is a function that is to be invoked n times.

Return Value:

It produces an array of returned values and this array is returned by the function.

Example 1: The below code example shows the basic implementation of the _.times() method of underscore.js.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
</head>
 
<body>
    <script>
        let n = 5
        let func = () => {
            console.log(`This function
                is called ${n} times \n`)
        }
 
        // The _.times function executes
        // the above func function n times
        _.times(n, func);
    </script>
</body>
 
</html>


Output:

Example 2: The below code example is another practical implementation of the _.times() method.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
</head>
 
<body>
    <script>
        let n = 5;
        let i = 1;
        let func = () => {
            for (i; i <= n; i++) {
                console.log(
                    `It is the function call ${i}`)
            }
        }
 
        // Calling the function func n times.
        let c = _.times(n, func);
        console.log(
            "array returned by times function: ", c)
    </script>
</body>
 
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads