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:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</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>
Output:
GeeksforGeeks
Example 2:
<!DOCTYPE html>
<html>
<head>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js">
</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>