Lodash _.inRange() Method
The _.inRange() method in Lodash is a utility function that checks if a given number is within a specified range. It’s a simple yet useful method for determining whether a number falls within a specified range. This function is particularly helpful when you need to perform conditional checks based on numeric ranges in your applications.
Syntax
_.inRange(number, start, end);
Parameters
- number: This parameter holds the number to check.
- start: This parameter holds the start value of the range.
- end: This parameter holds the end value of the range.
Return Value: This method returns true if the number is in the range, else false.
Example 1: In this example, we are checking whether the given value is present between the given start and end number, also start number is inclusive.
// Requiring the lodash library
const _ = require("lodash");
// Use of _.inRange method
console.log(_.inRange(12, 10));
console.log(_.inRange(10, 12));
console.log(_.inRange(5.6, 5));
console.log(_.inRange(5.6, 6));
Output
false
true
false
true
In this example
_.
inRange(12, 10) returns false because 12 is not between 0 and 10.- _.inRange(10, 12) returns true because 10 is within the range 0 to 12 (with 0 being the default start).
- _.inRange(5.6, 5) returns false because 5.6 is not less than 5.
- _.inRange(5.6, 6) returns true because 5.6 is within the range 0 to 6 (start = 0, end = 6).
Example 2: In this example, we are checking whether the given value is present between the given start and end number and printing the result in the console.
// Requiring the lodash library
const _ = require("lodash");
// Use of _.inRange method
console.log(_.inRange(2, 3, 5));
console.log(_.inRange(2, 2, 4));
console.log(_.inRange(4, 2, 4));
console.log(_.inRange(-2, -1, -5));
Output
false
true
false
true
In this example
- _.inRange(2, 3, 5) returns false because 2 is not between 3 and 5.
- _.inRange(2, 2, 4) returns true because 2 is between 2 and 4 (2 is inclusive).
- _.inRange(4, 2, 4) returns false because 4 is not less than 4 (the end value is exclusive).
- _.inRange(-2, -1, -5) returns true because -2 is between -1 and -5 (the range is adjusted to handle negative numbers).
Conclusion
The _.inRange() method is a simple and useful function in Lodash to check if a number falls within a specified range. Whether you are working with positive or negative ranges, this method makes range checking easy by handling edge cases and adjusting the range parameters as needed.