Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

JavaScript - check if number is odd in Vanilla JS

0 contributions
3 points

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more