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:
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