To check if a number is odd in JavaScript, we can use the modulus operator %
. The modulus operator gives us the remainder of a division operation. If we divide an odd number by 2, there will be a remainder of 1. So, checking if the remainder of the number divided by 2 is 1 will tell us if the number is odd or not. Here's an example:
index.tsx160 chars9 lines
We define a function called isOdd
which takes a num
parameter. Inside the function, we use the modulus operator to check if num
divided by 2 has a remainder of 1. If it does, we return true
, which means the number is odd. If there is no remainder, we return false
, which means the number is even. We then call the function with some example numbers to demonstrate how it works.
gistlibby LogSnag