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 named isInRange that takes three parameters: the value to check, the minimum allowed value, and the maximum allowed value.

  • Number.isFinite(value): This crucial step ensures that the input value is a finite number before proceeding with any comparisons. If value is NaN (Not a Number), infinity, or some other non-finite type, the function immediately returns false.

  • value >= min && value <= max: This condition checks if the value falls within the specified range, inclusive of both min and max.

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