Open In App

Underscore.js _.fnull() Method

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:

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.




// Defining underscore contrib variable
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.




// Defining underscore contrib variable
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.




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
function func(val) {
    return val;
}
  
safeVal = _.fnull(func, 10);
  
console.log(safeVal(null));

Output:

10

Article Tags :