Open In App

Underscore.js _.fnull() Method

Last Updated : 17 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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




// 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.

Javascript




// 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.

Javascript




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


Output:

10


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads