How do I check if a variable is an integer in JavaScript without using Number.isInteger()?
Alex K
alex k profile pic

To check if a variable is an integer in JavaScript without usingNumber.isInteger(), you can use a combination of type checking and mathematical operations. Here's an example implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

function isInteger(value) {
  // Check if the value is a number and is finite
  if (typeof value !== 'number' || !isFinite(value)) {
    return false;
  }
  
  // Check if the value is a whole number
  return Math.floor(value) === value;
}

// Example usage
console.log(isInteger(42)); // true
console.log(isInteger(3.14)); // false
console.log(isInteger('42')); // false
console.log(isInteger(null)); // false

In this implementation, theisInteger function first checks if the value is a number and is finite usingtypeof andisFinite checks. If the value is not a number or is not finite, it immediately returnsfalse. Next, if the value is a number, it checks if it is a whole number by comparing it with its floor value usingMath.floor(). If the floor value and the original value are the same, it means the value is an integer, and the function returnstrue. Note that this implementation considersNaN andInfinity as non-integers. If you want to includeInfinity as an integer, you can modify theisFinite check accordingly.