Syntax, Parameter and Return Value
Syntax:
_.divide(dividend, divisor)
Parameters:
-
dividend (Number): The first number (dividend).
- divisor (Number): The second number (divisor).
Return Value:
(Number) - Returns the result of dividing dividend by divisor.
Examples
Basic Division Operation:
JavaScript
var _ = require('lodash');
console.log(_.divide(6, 3));

You can also try this code with Online Javascript Compiler
Run Code
Output:
2
Demonstrates a simple division operation using _.divide().
Using in Calculations:
JavaScript
var total = 100;
var numberOfItems = 4;
var pricePerItem = _.divide(total, numberOfItems);
console.log(pricePerItem);

You can also try this code with Online Javascript Compiler
Run Code
Output:
25
Shows how _.divide() can be used in a basic arithmetic calculation to find the price per item.
Chaining with Other Lodash Operations:
JavaScript
var results = _([120, 180, 240]).map(total => _.divide(total, 3)).value();
console.log(results);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[40, 60, 80]
An example of chaining _.divide() with other Lodash methods for processing an array.
Handling Division in Data Transformation:
JavaScript
var data = { totalCost: 200, totalItems: 5 };
var averageCost = _.divide(data.totalCost, data.totalItems);
console.log(averageCost);

You can also try this code with Online Javascript Compiler
Run Code
Output:
40
Demonstrates using _.divide() for calculating averages in data transformation.
Frequently Asked Questions
How does _.divide() handle division by zero?
Similar to native JavaScript, dividing by zero using _.divide() will result in Infinity or -Infinity, depending on the sign of the dividend.
Is _.divide() necessary for simple division operations?
For basic division, native JavaScript operations are usually sufficient. _.divide() is more about consistency in coding style, particularly in projects heavily utilizing Lodash for data manipulation.
Can _.divide() handle non-numeric inputs?
If non-numeric values are passed to _.divide(), the result may be NaN (Not a Number), similar to JavaScript's native division behavior with invalid inputs.
Conclusion
Lodash's _.divide() method offers a straightforward and readable way to perform division operations in JavaScript. It aligns well with the Lodash ecosystem, providing a consistent approach to arithmetic alongside other data manipulation tasks.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.