My Development Notes


Whether a number is odd or even – JavaScript


Question

How to find out whether a number is odd or even using JavaScript code?

Solution 1

function oddEven(number) {
  if (number % 2 === 0) {
    return "even";
  } else {
    return "odd";
  }
}

console.log(oddEven(7));
// outputs 'odd'

Solution 2

var oddOrEven = (n) => (n & 1 ? "Odd" : "Even");

console.log(oddOrEven(228));
// returns 'Even'

Note: Here I’ve used the Bitwise AND rule. Refer JavaScript Bitwise AND documentation to know why this works. In the above code, n & 1 returns odd and everything else returns even numbers as per the rule.

Solution 3

const odd_or_even = (number) => (number % 2 ? "odd" : "even");

console.log(odd_or_even(91));
//returns 'odd'

Solution 4

const evenOdd = (n) => ["Even"][n % 2] || "Odd";

console.log(evenOdd(724));
//returns 'Even'

Solution 5

function even_odd(number) {
  return Math.abs(number) % 2 ? "Odd" : "Even";
}

console.log(even_odd(44));
// outputs 'Even'

Solution 6

let result;

function evenOrOdd(number) {
  if (number % 2 == 0) {
    result = `This is Even`;
  } else {
    result = `This is Odd`;
  }

  return result;
}

console.log(evenOrOdd(444));
// output : This is Even

Leave a Reply

Your email address will not be published. Required fields are marked *