Underscore.js _.result() Function

Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke etc even without using any built-in objects.

The _.result() function is an inbuilt function in Underscore.js library of JavaScript. Here, if the stated value of the named property is a function then you should call it with the object as a context else return it. Moreover, if a default value is stated and the property parameter is not given or is not defined then the default value will be returned.

Note: If the stated defaultValue is a function then its result will be returned as output.

Syntax:

_.result(object, property, [defaultValue])

Parameters: It accepts three parameters which are specified below:



  • object: It is the stated object.
  • property: It is the property stated.
  • [defaultValue]: It is the stated default value.

Return Value: This method returns the value of the named property.

Example 1:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <script>
        var obj = { 
            CSportal: 'GeeksforGeeks'
            gfg: function () { return 'Geeks!'; } 
        };
  
        // Calling result method with its parameters
        console.log(_.result(obj, 'CSportal'));
    </script>
</body>
  
</html>

chevron_right


Output:

GeeksforGeeks

Example 2:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <script>
        var obj = [1, 2, 4, 5];
  
        // Calling result method 
        // with its parameters
        console.log(_.result(obj, 9, 7));
        console.log(_.result(obj, 5));
    </script>
</body>
  
</html>

chevron_right


Output:

7
undefined

Reference: https://underscorejs.org/#result

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.