Question 10

Question

How would you determine if a value is an integer without using typeof or any other built-in methods?

Answer

Here's how you can check if a value is an integer without relying on built-in methods like typeof or special functions:

function isInteger(value) {
  return (
    Number.isFinite(value) && // Ensures it's a finite number 
    value % 1 === 0 // Checks for divisibility by 1, a key property of integers
  );
}

console.log(isInteger(5));   // Output: true
console.log(isInteger(3.14)); // Output: false
console.log(isInteger(-7));  // Output: true

Explanation:

  1. Number.isFinite(value): This step is crucial to rule out NaN (Not a Number) and other non-finite values, ensuring we're dealing with a potential integer. 2. value % 1 === 0: The modulus operator (%) calculates the remainder of a division. An integer divided by 1 always has a remainder of 0. This condition effectively checks if there's any fractional part to the number.

Key Points:

  • This approach relies on the fundamental mathematical property of integers: they have no fractional parts.

  • Limitations: While this method works well for most cases, it might not handle edge cases perfectly (e.g., very large numbers with potential precision issues).

Last updated