Explain Codes LogoExplain Codes Logo

How to check if a number is between two values?

javascript
functions
callbacks
promises
Anton ShumikhinbyAnton Shumikhin·Aug 28, 2024
TLDR

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:

let isBetween = (x, a, b) => a <= x && x <= b; // Usage: isBetween(2, 1, 3) -> true (2 is the life between 1 and 3)

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:

Number.prototype.isBetween = function (a, b) { return a <= this && this <= b; }; // Usage (10).isBetween(5, 15); // true (10 enjoys being sandwiched between 5 and 15)

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:

let isBetween = (x, a, b) => { const bottom = Math.min(a, b); // don't fall, it's the bottom const top = Math.max(a, b); // are we there yet? return bottom <= x && x <= top; };

Wrapping the range check in a function

To ensure better maintainability, enclose the range logic within a function:

function checkRange(x, lowerLimit, upperLimit, inclusive = true) { return inclusive ? lowerLimit <= x && x <= upperLimit // being inclusive, allowing 'x' to touch the boundaries : lowerLimit < x && x < upperLimit; // it's exclusive, 'x' cannot touch the edges }

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:

// Usage _.inRange(myNumber, 500, 601); // 600 is inclusive in this case

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:

function isNumber(value) { return typeof value === 'number' && isFinite(value); }

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:

if (isBetween(window.innerWidth, 1024, 1280)) { console.log('The window size is "just right" for this layout.'); // spews if size is fit for Goldilocks }

Tailor your range checks to suit the specific context and enrich both functionality and user experience.