How to use forEach Loop In Javascript
- Declare an array called “numbers” containing a set of integers.
- Declare an empty array called “even”.
- Use the forEach method to iterate through each element in the “numbers” array.
- Within the forEach loop, use an if statement to check if the current element is even using the modulus operator (element%2==0).
- If the element is even, use the push method to add it to the “even” array.
- After the forEach loop, use console.log () to display the message “Even numbers in an array are: [even numbers]” where [even numbers] is the array of even numbers.
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
Javascript
// 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
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:
Table of Content
- Using for Loop
- Using while Loop
- Using forEach Loop
- Using filter Method
- Using for…of Loop
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]