January 27, 2022

Blog @ Munaf Sheikh

Latest news from tech-feeds around the world.

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); 
example = 12;
Number.isInteger(example); 
example = Infinity;
Number.isInteger(example); 

Non-numeric values will return false, even if the value is an instance of the Number class.

Number.isInteger(null); 
Number.isInteger('42'); 
Number.isInteger(new Number(5)); 

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); 

example = 5 + 5e-16;
Number.isInteger(example); 

More Fundamentals Tutorials



Source link