Skip to content

Lodash - Number

Lodash provides helpful utility functions specifically designed for working with numbers, offering convenient ways to constrain values, check ranges, and generate random numbers.

Method & SyntaxDescriptionExample
_.clamp(number, [lower], upper)Clamps number within the inclusive lower and upper bounds. If lower is not provided, it defaults to 0.javascript<br>_.clamp(-10, -5, 5); // => -5<br>_.clamp(10, -5, 5); // => 5<br>_.clamp(2, 5); // Clamps between 0 and 5 => 2<br>_.clamp(8, 5); // Clamps between 0 and 5 => 5<br>
_.inRange(number, [start=0], end)Checks if number is between start and end. If end is not specified, it’s set to start with start becoming 0. If start > end, parameters are swapped. Checks are exclusive of end.javascript<br>_.inRange(3, 2, 4); // => true<br>_.inRange(4, 8); // (start=0, end=8) => true<br>_.inRange(4, 2); // (start=0, end=2) => false<br>_.inRange(2, 2); // (start=0, end=2) => false<br>_.inRange(1.5, 1, 2); // => true<br>_.inRange(5, 6, 4); // Swaps to (4, 6) => true<br>
_.random([lower=0], [upper=1], [floating])Produces a random number between lower and upper bounds (inclusive). If only one argument is provided, it returns a number between 0 and that number. If floating is true, or either bound is a float, a floating-point number is returned instead of an integer.javascript<br>_.random(0, 5); // => an integer between 0 and 5<br>_.random(5); // => an integer between 0 and 5<br>_.random(5, true); // => a float between 0 and 5<br>_.random(1.2, 5.2); // => a float between 1.2 and 5.2<br>_.random(0, 10, false); // Force integer result<br>

These number utilities provide convenient shortcuts for common numerical tasks that might otherwise require more verbose custom code.

Explore more number-related functions in the official Lodash Number documentation.