Thursday, October 9, 2025
HomeLanguagesJavascriptLodash _.defaultTo() Method

Lodash _.defaultTo() Method

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.

The _.defaultTo() method is used to check the given value and determine if a default value should be restored in its place. When the value is NaN, null, or undefined, the value given in the defaultValue parameter is returned.

Syntax:

_.defaultTo( value, defaultValue )

Parameters: This method accepts two parameters as mentioned above and described below:

  • value: This parameter holds the value to check.
  • defaultValue: This parameter holds the default value to be restored.

Return Value: This method returns the resolved value.

Example 1:

Javascript




// Requiring the lodash library  
const _ = require("lodash");  
  
// Return the resolved value 
// by _.defaultTo() method
console.log(_.defaultTo(5, 15));
  
// Return the resolved value
// by _.defaultTo() method
console.log(_.defaultTo(82, 43));


Output:

5
82

Example 2:  

Javascript




// Requiring the lodash library  
const _ = require("lodash");  
  
// When the value is NaN, defaultValue 
// is returned by _.defaultTo() method
console.log(_.defaultTo(null, 15));
  
// When the value is undefined, defaultValue 
// is returned by _.defaultTo() method
console.log(_.defaultTo(undefined, 43));


Output:

15
43
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
32342 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6712 POSTS0 COMMENTS
Nicole Veronica
11875 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11937 POSTS0 COMMENTS
Shaida Kate Naidoo
6833 POSTS0 COMMENTS
Ted Musemwa
7092 POSTS0 COMMENTS
Thapelo Manthata
6786 POSTS0 COMMENTS
Umr Jansen
6789 POSTS0 COMMENTS