Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Setting Default Value for Potentially Undefined Variable:
4.2.
JavaScript
4.3.
Handling Null Values in Data Processing:
4.4.
JavaScript
4.5.
Preventing NaN in Mathematical Operations:
4.6.
JavaScript
4.7.
Using with Optional Object Properties:
4.8.
JavaScript
5.
Frequently Asked Questions
5.1.
What types of values are considered invalid by _.defaultTo()?
5.2.
How does _.defaultTo() differ from logical OR (||) operator?
5.3.
Is _.defaultTo() commonly used in real-world applications?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.defaultTo() Method

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In programming, particularly in JavaScript, handling default values for potentially undefined or null variables is a common task. Lodash's _.defaultTo() method provides a straightforward way to specify a default value for a variable if the original value is NaN, null, or undefined. 

Lodash _.defaultTo() Method

This function is especially useful in ensuring that functions or operations have valid data to work with, thereby avoiding errors due to invalid or missing inputs.

Why This Function is Used

The _.defaultTo() function is used to assign a default value to a variable if the original value is not valid (i.e., is NaN, null, or undefined). It's crucial in scenarios where variables might not be initialized or could be set to values that are not suitable for further processing, ensuring that subsequent code can execute without errors related to invalid data.

Syntax, Parameter and Return Value

Syntax: 

_.defaultTo(value, defaultValue)

Parameters:

  • value: The value to check for validity.
     
  • defaultValue: The default value to return if the original value is invalid.

Return Value: 

Returns the resolved value (either the original value if valid, or the default value).

Examples 

Setting Default Value for Potentially Undefined Variable:

  • JavaScript

JavaScript

var _ = require('lodash');

var possiblyUndefined = undefined;

var safeValue = _.defaultTo(possiblyUndefined, 10);

console.log(safeValue);
You can also try this code with Online Javascript Compiler
Run Code

Output: 

10


Demonstrates using _.defaultTo() to set a default value when the original variable is undefined.

Handling Null Values in Data Processing:

  • JavaScript

JavaScript

var userAge = null;

var ageForProcessing = _.defaultTo(userAge, 18);

console.log(ageForProcessing);
You can also try this code with Online Javascript Compiler
Run Code

Output: 

18


Shows setting a default value for a variable that might be null.

Preventing NaN in Mathematical Operations:

  • JavaScript

JavaScript

function calculateDiscount(price, discount) {

 discount = _.defaultTo(discount, 0);

 return price - (price * discount);

}

console.log(calculateDiscount(100, NaN));
You can also try this code with Online Javascript Compiler
Run Code

Output:

 100


An example of using _.defaultTo() to avoid NaN results in calculations.

Using with Optional Object Properties:

  • JavaScript

JavaScript

var config = { timeout: null };

var timeoutValue = _.defaultTo(config.timeout, 1000);

console.log(timeoutValue);
You can also try this code with Online Javascript Compiler
Run Code

Output:

 1000


Demonstrates setting a default value for an optional property in an object.

Frequently Asked Questions

What types of values are considered invalid by _.defaultTo()?

_.defaultTo() considers NaN, null, and undefined as invalid values. Other falsy values like 0, '', and false are considered valid.

How does _.defaultTo() differ from logical OR (||) operator?

The logical OR operator (||) treats all falsy values (0, '', false, null, undefined, NaN) as invalid, whereas _.defaultTo() specifically checks for null, undefined, and NaN.

Is _.defaultTo() commonly used in real-world applications?

_.defaultTo() is particularly useful in applications where robustness and error handling are important, especially in dealing with external data or user inputs.

Conclusion

Lodash's _.defaultTo() method is an effective tool for ensuring that variables have valid values, providing a simple way to set default values in case of null, undefined, or NaN. It enhances code reliability by preventing errors related to invalid data.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass