Open In App

JavaScript program to print even numbers in an array

Given an array of numbers and the task is to write a JavaScript program to print all even numbers in that array.

We will use the following methods to find even numbers in an array:



Example:



Input:    numbers_array1= [4, 76, 89, 61, 72, 64]
Output: [4,76,72,64]
Input:   numbers_array2= [15, 60, 90, 14, 7, 45]
Output: [60,90,14]

Method 1: Using for Loop 

Example: In this example, we are Using for Loop




// Initializing numbers array
let numbers = [10, 23, 12, 21];
 
// Declaring empty Even array
let even = [];
for(let i = 0; i < numbers.length; i++) {
       if (numbers[i] % 2 == 0)
       even.push(numbers[i]);
}
 
// Printing output
console.log(`Even numbers in an array are: ${even}`);

Output
Even numbers in an array are: 10,12

Method 2: Using while Loop 

Example: In this example, we are Using while Loop 




// Initializing numbers array
let numbers=[44, 26, 48, 64, 27, 53];
 
// Declaring empty Even array
let even = [];
let i = 0;
while(i < numbers.length) {
       if (numbers[i] % 2 == 0)
       even.push(numbers[i]);
       i++;
}
 
// Printing output
console.log(`Even numbers in an array are: ${even}`)

Output
Even numbers in an array are: 44,26,48,64

Method 3: Using forEach Loop

This approach allows one to iterate through the entire array, check each element for even-ness, and add even numbers to a separate array, which is then displayed in the console.

Example: In this example, we are Using forEach Loop




// Initializing numbers array
let numbers = [86, 41, 55, 85, 90, 24];
 
// Declaring empty Even array
let even = [];
numbers.forEach(element => {
    if( element%2 == 0 )
    even.push(element);
});
 
// Printing output
console.log(`Even numbers in an array are: ${even}`);

Output
Even numbers in an array are: 86,90,24

Method 4: Using filter Method

The filter method returns a new array with all elements that pass the test implemented by the callback function.

Example: In this example, we are Using filter Method




// Initializing numbers array
let numbers = [86, 41, 55, 85, 90, 24];
 
let evenNumbers = numbers.filter(function(element) {
      return element % 2 === 0;
});
 
// Printing output
console.log(`Even numbers in an array are: ${evenNumbers}`);

Output
Even numbers in an array are: 86,90,24

Method 5: Using for…of Loop

The for…of loop iterates over the iterable objects (like Array, Map, Set, arguments object, …,etc), invoking a custom iteration hook with statements to be executed for the value of each distinct property.

Example: In this example, we are Using for…of Loop




const even = [];
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const num of arr) {
    if (num % 2 === 0) {
        even.push(num);
    }
}
console.log(even);

Output
[ 2, 4, 6, 8 ]


Article Tags :