checkIfInteger()
As you know if you have been reading my recent posts, I have been practicing writing algorithms for my next tech interviews. In this installment I am going to walk you trough creating a function that checks if the input is an integer in javascript. An integer is a whole number, or a number with no decimal. There are a couple way that you could go about solving this problem, the solution I went with is to us the modulus (division remainder) operator. This operator will return us the remainder of a division statement for example
10 % 6
would return
4
Any integer should have a remainder of 0 if divided by 1 but a float like the next example will have a remainder of the numbers after the decimal.
5.5 % 1
would return
0.5
where
5 % 1
returns
0
This being said, my solution was to find if the the number given using the modulus operator === 0. Here is the solution
const checkIfInteger = (num) => num % 1 === 0
This will return true if there is a remainder of 0 and false if the remainder is anything else. I hope this helped!