How to usethe Modulo Operator in JavaScript in Javascript

The Modulo Operator is used to get the remainder, The number will be an even number if it gives zero after taking the modulo with 2 else it will be an odd number.

Example: It describes how we can count the number of even and odd numbers present in an array using the modulo operator

Javascript




// Creating an Array
let array = [1, 2, 3, 4, 5, 6];
  
// Count of odd number and
// even number 
// will be zero initially
let oddNum = 0;
let evenNum = 0;
  
// For loop for counting 
// odd and even number 
for (let index = 0; index < array.length; index++) {
    if (array[index] % 2 == 0) {
        evenNum++;
    }
    else {
        oddNum++;
    }
}
  
// Printing the result
console.log("Total even number: " + evenNum);
console.log("Total odd number: " + oddNum);


Output

Total even number: 3
Total odd number: 3

JavaScript Program to Count Even and Odd Numbers in an Array

In this article, we will write a program to count Even and Odd numbers in an array in JavaScript. Even numbers are those numbers that can be written in the form of 2n, while Odd numbers are those numbers that can be written in the form of 2n+1 form.

For finding out the Even and Odd numbers in an array there are various methods:

  • Using Modulo Operator
  • using Bitwise & Operator
  • Using Bitwise OR Operator (|)
  • Using Ternary Operator

Similar Reads

Approach 1: Using the Modulo Operator in JavaScript

The Modulo Operator is used to get the remainder, The number will be an even number if it gives zero after taking the modulo with 2 else it will be an odd number....

Approach 2: Using Bitwise & Operator

...

Approach 3: Using Bitwise OR Operator (|)

It is an another approach via we can find out the number is odd or even. It chceks for the binary number of the given number if the last bit of that binary number is 1 then it will be odd else it will be even....

Approach 4: Using Ternary Operator

...