Search code snippets, questions, articles...

Lodash - Check if a number is within the Range(without if-else)

If you want to check a number that exists between the range of two numbers without using if-else statements then you can use the inRange() function of Lodash to do that.
const number = 10
const start_range = 5;
const end_range = 20;

const num_in_range = _.inRange(number, start_range, end_range);

if (num_in_range) {
    console.log("Number is within the range");
} else {
    console.log("Nomber is not in range");
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool


Number is within the range

Try it yourself

We are using the _.inRange() function of the Lodash library here. The function takes a number, start range, and end range as a parameter. If the start range is not provided, it will assign a default value of 0 to it.

If the number is within the range, the function will return true or else false. Below are some code examples that can be helpful to understand the working of the _.inRange() function.

Code Examples

// check if 7 is within range 8 to 10
console.log(_.inRange(7, 8, 10));
// -> false

// check if -7 is within range -4 to -11
console.log(_.inRange(-7, -4, -11));
// -> true

// check if 8 is within range 0 to 9
console.log(_.inRange(8, 9));
// -> true

// check if 11 is within range 0 to 8
console.log(_.inRange(11, 8));
// -> false

// check if 4.2 is within range 0 to 5
console.log(_.inRange(4.2, 5));
// -> true

Try it yourself

Was this helpful?