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); |
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