Ad

Checks whether a number is odd or even by using bitwise AND (&) operator.


Visualised

isOdd(9) // returns 1 (true)
1001 (9 in decimal)
0001 (1 in decimal)
   &
----
0001

isOdd(6) // returns 0 (false)
0110 (6 in decimal)
0001 (1 in decimal)
   &
----
0000 (0 in decimal)

Since odd numbers in binary always end with 1 at the lowest-order bit all we need is to check that bit and call it a day.

Code
Diff
  • const isOdd = n => n & 1
    • const number = prompt("Enter a number: ");
    • if(number % 2 == 0){
    • console.log("The number is even.");
    • }else{
    • console.log("The number is odd.");
    • }
    • const isOdd = n => n & 1