Underscore.js _.fnull() Method
Last Updated :
17 Aug, 2020
The _.fnull() method returns a function that protects the given function from receiving non-existing values. When the fnull() function receives a non-existing value, default safe value is returned.
Syntax:
_.fnull( function, default );
Parameters: This method accepts two parameters as mentioned above and described below:
- function: It is a given function that contains return logic.
- default: The value that is used when the method receives a non-existing value
Return Value: This method returns a function.
Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed.
underscore.js contrib library can be installed using npm install underscore-contrib –save.
Example 1: In this example, when undefined is passed, the function returns the default safe value.
Javascript
var _ = require( 'underscore-contrib' );
function func(val) {
return val;
}
safeVal = _.fnull(func, "GeeksforGeeks" );
console.log(safeVal(undefined));
|
Output:
GeeksforGeeks
Example 2: when the existing value is passed default value is not used.
Javascript
var _ = require( 'underscore-contrib' );
function func(val) {
return val;
}
safeVal = _.fnull(func, "GeeksforGeeks" );
console.log(safeVal( "GFG" ));
|
Output:
GFG
Example 3: This method can also be used for integers.
Javascript
var _ = require( 'underscore-contrib' );
function func(val) {
return val;
}
safeVal = _.fnull(func, 10);
console.log(safeVal( null ));
|
Output:
10
Share your thoughts in the comments
Please Login to comment...