How to Check if a Variable is an Integer in JavaScript
Jan 13, 2022
To check if a variable is an integer in JavaScript, use Number.isInteger()
.
Number.isInteger()
returns true
or false
depending on the parameter provided.
let example = 12.1;
Number.isInteger(example); // false
example = 12;
Number.isInteger(example); // true
example = Infinity;
Number.isInteger(example); // false
Non-numeric values will return false, even if the value is an instance of the Number
class.
Number.isInteger(null); // false
Number.isInteger('42'); // false
Number.isInteger(new Number(5)); // false
Remember that JavaScript can only represent up to 16 decimal places, so Number.isInteger()
may return surprising results in cases where JavaScript doesn't have sufficient numeric precision to represent the output.
let example = 5 + 1e-16;
Number.isInteger(example); // true
example = 5 + 5e-16;
Number.isInteger(example); // false
More Fundamentals Tutorials
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript
- Validate Emails using Regex in JavaScript
- JavaScript Copy to Clipboard