There are a couple of ways we can use JavaScript to count the even numbers in an array. One of the simplest ways is to just use a for loop to loop through each number in the array and count the even ones.

var count = 0;
for ( var i = 0; i

Let's put this code in a function to make it easier to count the even numbers in an array.

function evenNumbers(arr){
var count = 0;
  for ( var i = 0; i

Now let's show some examples of this function in action.

function evenNumbers(arr){
var count = 0;
  for ( var i = 0; i

When working with collections of data, the ability to easily summarize and get statistics about the collection is valuable.

One such case is if you want to count the even numbers in an array.

To count the even numbers in an array in JavaScript, one of the easiest ways is with a for loop. To get the even numbers, we just need to check if the number is even or odd.

Once again is our simple function showing you how to count the number of even numbers in an array using JavaScript.

function evenNumbers(arr){
var count = 0;
  for ( var i = 0; i

Using the Filter Method to Count the Even Numbers in an Array

If we want an even simpler way to count the even numbers in an array, we can make use of the JavaScript filter() method.

var count = someArray.filter(num => {
  return num % 2 == 0;
});

The filter method above will return a new array of just even numbers, which will be assigned to the variable count.

We can then just use the length property on our new array to see how many even numbers are in our original array.

We'll put this code in a function to make it very simple to get even numbers in an array.

function evenNumbers(arr){
  var count = arr.filter(num => {
    return num % 2 == 0;
  });
  return count.length;
};

Let's test this function with our same array of numbers from above to see if we get the same result:

function evenNumbers(arr){
  var count = arr.filter(num => {
    return num % 2 == 0;
  });
  return count.length;
};

var array1 = [0,1,2,3,4,5,6,7,8,9];

console.log(evenNumbers(array1));

#Output
5

Hopefully this article has been useful for you to learn how to use JavaScript to count the even numbers in an array.

Categorized in:

JavaScript,

Last Update: March 12, 2024