DEV Community

Dhairya Shah
Dhairya Shah

Posted on

Determine Odd / Even Numbers using JavaScript

In this article, we are going to talk about numbers, odd and even numbers with some JavaScript.

Let's gets started,

  • Choose a random number
let number = 24
Enter fullscreen mode Exit fullscreen mode
  • As we know this number is even, but let's check this with JavaScript
if(number % 2 === 0){
        console.log(`${number} is an even number`)
}else{
        console.log(`${number} is odd number`)
}
Enter fullscreen mode Exit fullscreen mode
  • This gives the following output,
// 24 is an even number
Enter fullscreen mode Exit fullscreen mode

This is how you can determine odd / even numbers using JavaScript.

By the way, I have a tutorial on it so make sure to check that out


Top comments (6)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

If you care about performance, it's actually quicker to use a bitwise test:

const isOdd = i => i&1
const isEven = i => 1&i^1
Enter fullscreen mode Exit fullscreen mode
Collapse
 
thebox193 profile image
Sir.Nathan (Jonathan Stassen)

I've never really understood bitwise operators.

Collapse
 
thebox193 profile image
Sir.Nathan (Jonathan Stassen)

Nifty! What other ways might you determine if a number is even or odd?
How might you use this to determine if a number is divisible by 5?

Collapse
 
dhairyashah profile image
Dhairya Shah

To Determine number is divisible by 5, you can try

let number = 150

if(number % 5 === 0){
        console.log(`${number} is divisible by five`)
}else{
        console.log(`${number} is not divisible by 5`)
}
// Output: 150 is divisible by five
Enter fullscreen mode Exit fullscreen mode
Collapse
 
thebox193 profile image
Sir.Nathan (Jonathan Stassen)

Nice! Makes sense!

Collapse
 
andrewbaisden profile image
Andrew Baisden

Works like a charm I use this code often when trying to separate odd from even.