Languages
[Edit]
EN

JavaScript - check if number is odd in Vanilla JS

3 points
Created by:
Root-ssh
6442

In this short article we will show you how in JavaScript check if number is odd.

Odd integer numbers are:

... -7  -5  -3  -1   1   3   5   7 ...

Simple test example:

// ONLINE-RUNNER:browser;

function isOdd(number) {
	return number % 2 !== 0;
}

console.log( isOdd(0) );  // false
console.log( isOdd(1) );  // true <------ odd
console.log( isOdd(2) );  // false
console.log( isOdd(3) );  // true <------ odd
console.log( isOdd(4) );  // false
console.log( isOdd(5) );  // true <------ odd

console.log( isOdd(-1) ); // true <------ odd
console.log( isOdd(-2) ); // false
console.log( isOdd(-3) ); // true <------ odd
console.log( isOdd(-4) ); // false
console.log( isOdd(-5) ); // true <------ odd

Alternative solution 1 - negative numbers conversion:

// ONLINE-RUNNER:browser;

function isOdd(number) {
	if (number < 0) {
		number = -number;;
	}
	return number % 2 === 1;
}

console.log( isOdd(0) );  // false
console.log( isOdd(1) );  // true <------ odd
console.log( isOdd(2) );  // false
console.log( isOdd(3) );  // true <------ odd
console.log( isOdd(4) );  // false
console.log( isOdd(5) );  // true <------ odd

console.log( isOdd(-1) ); // true <------ odd
console.log( isOdd(-2) ); // false
console.log( isOdd(-3) ); // true <------ odd
console.log( isOdd(-4) ); // false
console.log( isOdd(-5) ); // true <------ odd

Alternative solution 2 - bitwise operator:

// ONLINE-RUNNER:browser;

function isOdd(number) {
	return (number & 1) > 0;
}

console.log( isOdd(0) );  // false
console.log( isOdd(1) );  // true <------ odd
console.log( isOdd(2) );  // false
console.log( isOdd(3) );  // true <------ odd
console.log( isOdd(4) );  // false
console.log( isOdd(5) );  // true <------ odd

console.log( isOdd(-1) ); // true <------ odd
console.log( isOdd(-2) ); // false
console.log( isOdd(-3) ); // true <------ odd
console.log( isOdd(-4) ); // false
console.log( isOdd(-5) ); // true <------ odd

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.