![]() |
VOOZH | about |
We are going to learn how to check whether the number is even or Odd using JavaScript. In the number system, any natural number that can be expressed in the form of (2n + 1) is called an odd number, and if the number can be expressed in the form of 2n is called an even number.
Here are the different approaches we can use in JavaScript to determine whether a number is odd or even:
The modulo operator gives the remainder when one number is divided by another. To check if a number is even or odd:
Odd
A faster way to check if a number is even or odd is by using the Bitwise AND Operator (&). This checks the last bit of a number.
Number is even Number is odd
The Bitwise OR Operator (|) compares two numbers bit by bit. It returns 1 for each bit position where at least one of the bits is 1. If both bits are 0, it returns 0. In simple words, the OR operator checks two bits and returns 1 if either of the bits is 1. If both bits are 0, it returns 0.
Even Odd
The if...else statement is a fundamental structure in JavaScript. It allows you to execute different blocks of code depending on whether a condition is true or false. This can be used to check if a number is odd or even.
The number is even.
The Ternary Operator is a shorthand for the if...else statement. It takes three operands: a condition, a result for true, and a result for false. This can be used to check whether a number is even or odd in one line.
The number is even.