Open In App

Underscore.js _.defaults() Function

Last Updated : 25 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Underscore.js _.defaults() function returns the object after filling in its undefined properties with the first value present in the following list of default objects.

Syntax:

_.defaults(object, *defaults);

Parameters:

  • object: This parameter holds the value of an object.
  • defaults: It is an optional parameter. It contains the [key, value] pair of an object.

Return Value:

It returns the object after filling in its undefined properties with the first value present in the following list of default objects.

Example 1: The below code example implements the _.defaults() function in underscore.js.

html
<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
    </script>
</head>

<body>
    <script type="text/javascript">
        const info = {
            Company: 'GeeksforGeeks',
            Address: 'Noida',
            Contact: '+91 9876543210'
        };

        console.log(_.defaults(info,
            {
                Contact: '+91 9898989898',
                Name: 'Rakesh'
            })
        ); 
    </script>
</body>

</html>

Output:

Example 2: This is another implementation of the _.defaults() function.

html
<!DOCTYPE html>
<html>

<head>
    <script type="text/javascript" src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
    </script>
</head>

<body>
    <script type="text/javascript">

        const info = {
            Company: 'GeeksforGeeks',
            Address: 'Noida',
            Contact: '+91 9876543210'
        };

        const def = {
            Name: 'Ashok',
            Age: '34',
            Company: 'GFG'
        }

        console.log(_.defaults(info, def)); 
    </script>
</body>

</html>

Output:


Next Article

Similar Reads