Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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.
Using _.cond() for Simple Conditional Logic:
4.2.
JavaScript
4.3.
Complex Conditional Logic:
4.4.
Using With Array Operations:
4.5.
JavaScript
4.6.
Error Handling:
4.7.
JavaScript
5.
Frequently Asked Questions
5.1.
How is _.cond() different from using multiple if-else statements?
5.2.
Can _.cond() handle asynchronous conditions or actions?
5.3.
Is there a limit to the number of condition-result pairs in _.cond()?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.cond() Method

Author Pallavi singh
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

In programming, handling complex conditional logic can become cumbersome and less readable, especially with multiple if-else statements. Lodash's _.cond() method offers a structured and readable alternative. 

Lodash _.cond() Method

This function creates a function that iterates over pairs of condition and result functions, executing the result function for the first truthy condition. It's particularly useful for simplifying and organizing intricate conditional logic in code.

Why This Function is Used

The _.cond() function is used to streamline complex conditional operations by mapping conditions to corresponding actions. Instead of using multiple if-else or switch statements, _.cond() allows for a more functional and declarative approach, improving code readability and maintainability.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter and Return Value

Syntax: 

_.cond(pairs)

Parameters:

pairs (Array): An array of condition-result pairs, each pair as an array with a predicate function and a corresponding function to execute.

Return Value: 

(Function) - Returns a new function that will check the conditions in the provided pairs and execute the corresponding function for the first truthy condition.

Examples 

Using _.cond() for Simple Conditional Logic:

  • JavaScript

JavaScript

var _ = require('lodash');

var classifyAge = _.cond([

 [age => age < 18, () => 'Child'],

 [age => age < 65, () => 'Adult'],

 [() => true, () => 'Senior']

]);

console.log(classifyAge(25));

console.log(classifyAge(70));

Output: 

'Adult'
'Senior'


Demonstrates classifying ages into categories based on conditions.

Complex Conditional Logic:

var handleEvent = _.cond([
  [event => event.type === 'click', () => handleOnClick(event)],
  [event => event.type === 'hover', () => handleOnHover(event)],
  [() => true, () => handleDefault(event)]
]);
// Usage
handleEvent({ type: 'click' });
handleEvent({ type: 'unknown' });


Shows handling different types of events with specific functions.

Using With Array Operations:

  • JavaScript

JavaScript

var processItems = _.cond([

 [items => _.isEmpty(items), () => 'No items to process'],

 [items => items.length > 5, () => 'Processing in batches'],

 [() => true, items => `Processing ${items.length} items`]

]);

console.log(processItems([]));

console.log(processItems([1, 2, 3, 4, 5, 6]));

Output: 

'No items to process'
'Processing in batches'


An example of processing arrays based on their length.

Error Handling:

  • JavaScript

JavaScript

var handleError = _.cond([

 [error => error.code === 404, () => 'Not found'],

 [error => error.code === 500, () => 'Internal server error'],

 [() => true, () => 'Unknown error']

]);

console.log(handleError({ code: 404 }));

Output: 

'Not found'


Demonstrates using _.cond() for error handling based on error codes.

Frequently Asked Questions

How is _.cond() different from using multiple if-else statements?

_.cond() provides a more structured and declarative approach to handling conditional logic, which can enhance readability and organization compared to multiple if-else statements.

Can _.cond() handle asynchronous conditions or actions?

_.cond() is designed for synchronous operations. For asynchronous conditions or actions, you would need to handle promises or async functions separately.

Is there a limit to the number of condition-result pairs in _.cond()?

There's no specific limit to the number of pairs, but it's advisable to keep the number reasonable for maintainability and readability.

Conclusion

Lodash's _.cond() method offers an elegant solution for handling complex conditional logic, mapping conditions to corresponding actions in a readable and maintainable format. It's a valuable tool for organizing and simplifying conditional operations in your code.

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.

Previous article
Lodash _.endsWith() Method
Next article
Lodash _.sum() Method
Live masterclass