How to check if a number is between two values?
When checking if x
is between [a, b]
, apply: a <= x && x <= b
. The answer will be true
if x
is within the range or on its edges.
Example:
Enhancing the basic approach
Checking if a number falls between two others in JavaScript is commonplace. While the basic check is straightforward, there are multiple ways to expand this functionality.
Convenience with prototyping
For improved code reuse and readability, consider extending the Number
prototype with a custom method:
Note, alter prototypes with caution, as it may disrupt other code segments unprepared for these changes.
Bound determination with Math methods
Unsure if the range boundaries are in order? Bring Math.min()
and Math.max()
into play:
Wrapping the range check in a function
To ensure better maintainability, enclose the range logic within a function:
Handling inclusive and exclusive ranges
The nature of a range (inclusive or exclusive) significantly influences its application. Thus, providing this option in your range checking function can be critical.
Exhaustive ways for checking a range
Leverage lodash library
If 'lodash' is used in your project, the _.inRange
function offers a quick range check:
Ensure you understand the specifics of any third-party libraries used via their respective documentation.
Range checking with validation
Before conducting range checks, ensure the variable is a number:
Performing this validation prevents baffling results, especially when working with external data or user inputs.
Incorporating conditionals
Integrate range checking within conditional statements, tailored to your application's specifics:
Tailor your range checks to suit the specific context and enrich both functionality and user experience.
Was this article helpful?