Languages
[Edit]
EN

JavaScript - check if number is odd in Vanilla JS

3 points
Created by:
Root-ssh
68440

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

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join