Question 8
Question
How would you implement a custom range checking function that uses Number.isFinite()
internally?
Answer
Here's how you can implement a custom range checking function in JavaScript, incorporating the power of Number.isFinite()
for robust validation:
function isInRange(value, min, max) {
return Number.isFinite(value) && value >= min && value <= max;
}
// Examples:
console.log(isInRange(5, 1, 10)); // Output: true (5 is within the range)
console.log(isInRange(20, 1, 10)); // Output: false (20 is outside the range)
console.log(isInRange(-1, 1, 10)); // Output: true (-1 is within the range)
console.log(isInRange(NaN, 1, 10)); // Output: false (NaN is not finite)
Explanation:
function isInRange(value, min, max)
: Defines a function namedisInRange
that takes three parameters: thevalue
to check, themin
imum allowed value, and themax
imum allowed value.Number.isFinite(value)
: This crucial step ensures that the inputvalue
is a finite number before proceeding with any comparisons. Ifvalue
is NaN (Not a Number), infinity, or some other non-finite type, the function immediately returnsfalse
.value >= min && value <= max
: This condition checks if thevalue
falls within the specified range, inclusive of bothmin
andmax
.
Key Points:
Robustness: By using
Number.isFinite()
, this function gracefully handles potential issues with invalid input types (like NaN), preventing unexpected behavior.Readability: The code is clear and concise, making it easy to understand its purpose and how it works.
Last updated