How to usethe modulo Operator in Javascript
In this method, we use the JavaScript Modulo Operator (%) to check whether the number is even or odd in JavaScript. We will evaluate the N % 2, and if the result is 0 then the number is even otherwise the number is odd.
Syntax:
remainder = var1 % var2
Example: In this example, we are using the modulo operator to find given number is even or odd.
// Returns true if n is
// even, else odd
function isEven(n) {
return (n % 2 == 0);
}
// Driver code
let n = 101;
isEven(n) ? console.log("Even") : console.log("Odd");
Output
Odd
JavaScript Program to Check if a Number is Odd or Even
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.
In other words, Those numbers that are completely divisible by 2 (give the remainder 0 after dividing by 2) are known as even numbers and those which divided by 2 and leave a reminder 1 are called odd numbers.
Even = {2k : k ∈ Z}
Odd = {2k + 1 : k ∈ Z}
where k is an integer.
Example:
Input: 2
Output: Even number
Input: 41
Output: Odd Number
There are several methods that can be used to Check if a Number is Odd or Even, which are listed below:
Table of Content
- Approach 1: Using the modulo Operator
- Approach 2: Using Bitwise & Operator
- Approach 3: Using Bitwise OR Operator (|)
- Approach 4: Using Ternary Operator