Friday, September 5, 2025
HomeLanguagesJavascriptUnderscore.js _.fnull() Method

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:

  • 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, "neveropen");
  
console.log(safeVal(undefined));


Output:

neveropen

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, "neveropen");
  
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
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32265 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6635 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11864 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7026 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6719 POSTS0 COMMENTS