DEV Community

Dhairya Shah
Dhairya Shah

Posted on

6 4

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

πŸ‘‹ Kindness is contagious

If this post resonated with you, feel free to hit ❀️ or leave a quick comment to share your thoughts!

Okay