Thought leadership from the most innovative tech companies, all in one place.

How to Check if a Value is Within a Range of Numbers in JavaScript

We can use the JavaScript’s greater than or equal to and less than or equal to operators to check if a number is in between 2 numbers. We can use the JavaScript’s greater than or equal to and less…

image

Photo by Pawel Kadysz on Unsplash

Sometimes, we want to check if a value is within a range of numbers in JavaScript. In this article, we’ll look at how to check if a value is within a range of numbers in JavaScript.

Use the Greater Than or Equal to and Less Than or Equal to Operators

We can use the JavaScript’s greater than or equal to and less than or equal to operators to check if a number is in between 2 numbers. For instance, we can write:

const between = (x, min, max) => {
  return x >= min && x <= max;
};
// ...
const x = 0.002;
if (between(x, 0.001, 0.009)) {
  // something
}

We create the between function with the x , min and max parameters. x is the number we want to check if it’s between min and max . Then we call it in the if statement to see if x is between 0.001 and 0.009.

Use the Lodash inRange Method

We can also use the Lodash inRange method to check if a number is in between 2 numbers. To use it, we write:

const x = 0.002;
if (_.inRange(x, 0.001, 0.009)) {
  // something
}

We call inRange with the number x that we want to check if it’s between 0.001 and 0.009.

Conclusion

We can use the JavaScript’s greater than or equal to and less than or equal to operators to check if a number is in between 2 numbers. Also, we can use the Lodash inRange method to do the same thing.




Continue Learning