How to Check if a Number is Between Two Numbers in JavaScript
A fundamental task in programming is to check if a number falls within a specific range. This is essential for validating input, filtering data, or controlling application logic. For example, you might need to verify that a user's age is between 18 and 65 or that a value is within an acceptable tolerance.
This guide will teach you the standard and most readable way to perform this check using basic comparison operators. You will learn how to create a simple, reusable function to handle both inclusive and exclusive ranges.
The Core Logic: Using && for Range Checking
The most straightforward way to check if a number is between two others is to use a combination of "greater than" (>) and "less than" (<) operators, linked by the logical AND (&&) operator.
The Syntax (Exclusive)
number > lowerBound && number < upperBound
This checks if the number is strictly greater than the lowerBound AND strictly less than the upperBound.
Basic Example: A Simple "In Range" Check
This script checks if a given score is within the range of 1 to 100, not including the boundaries.
const score = 85;
const minScore = 0;
const maxScore = 100;
let isInRange = false;
// Check if score is greater than 0 AND less than 100
if (score > minScore && score < maxScore) {
isInRange = true;
}
if (isInRange) {
console.log(`The score ${score} is within the valid range.`);
} else {
console.log(`The score ${score} is out of range.`);
}
Output:
The score 85 is within the valid range.
Handling Inclusive vs. Exclusive Ranges
The boundary conditions are very important.
- Exclusive Range: The number is between the boundaries but not equal to them (e.g.,
(0, 100)). Use>and<. - Inclusive Range: The number can be equal to the boundaries (e.g.,
[0, 100]). Use>=and<=.
Inclusive Example:
const score = 100;
const minScore = 0;
const maxScore = 100;
// Checks if score is greater than or equal to 0 AND less than or equal to 100
if (score >= minScore && score <= maxScore) {
console.log('The score is valid.');
} else {
console.log('The score is invalid.');
}
Output:
The score is valid.
Exclusive Example:
const score = 100;
const minScore = 0;
const maxScore = 100;
// Checks if score is greater than 0 AND less than 100
if (score > minScore && score < maxScore) {
console.log('The score is valid.');
} else {
console.log('The score is invalid.');
}
Output:
The score is invalid.
Creating a Reusable Function (Best Practice)
For clean and maintainable code, you should encapsulate this logic in a reusable function. This function can also handle cases where you don't know if num1 or num2 is the lower bound.
function isBetween(number, num1, num2, inclusive = false) {
// Find the minimum and maximum of the two boundary numbers
const min = Math.min(num1, num2);
const max = Math.max(num1, num2);
if (inclusive) {
return number >= min && number <= max;
}
return number > min && number < max;
}
// --- Examples ---
// Exclusive check (default)
console.log(`Is 5 between 1 and 10? ${isBetween(5, 1, 10)}`); // Output: true
console.log(`Is 10 between 1 and 10? ${isBetween(10, 1, 10)}`); // Output: false
// Inclusive check
console.log(`Is 10 between 1 and 10 (inclusive)? ${isBetween(10, 1, 10, true)}`); // Output: true
// Handles swapped boundaries automatically
console.log(`Is 5 between 10 and 1? ${isBetween(5, 10, 1)}`); // Output: true
Output:
Is 5 between 1 and 10? true
Is 10 between 1 and 10? false
Is 10 between 1 and 10 (inclusive)? true
Is 5 between 10 and 1? true
How it Works:
Math.min()andMath.max(): These functions reliably find the lower and upper bounds, so you don't have to worry about the order of the arguments.inclusive = false: This sets a default value for theinclusiveparameter, making the check exclusive unless you explicitly passtrue.
A Note on Performance and Readability
For this common task, the simple number > min && number < max pattern is extremely performant and is the most readable and universally understood solution in JavaScript. While libraries like Lodash offer an _.inRange function, it is not necessary to add a library for such a fundamental operation unless you are already using it in your project. The native JavaScript solution is clear, efficient, and requires no external dependencies.
Conclusion
Checking if a number is between two others is a simple but fundamental logical operation in JavaScript.
The key takeaways are:
- The standard method is to use the comparison operators combined with the logical AND operator:
num > min && num < max. - Use
>=and<=if you want the range to be inclusive of the boundary values. - For robust and reusable code, create a simple
isBetween()helper function that handles the logic for you. - Use
Math.min()andMath.max()inside your function to avoid errors if the boundary arguments are swapped.