How to use forEach Loop In Javascript
In this method, it combines a “for” loop with a “forEach” loop to identify even numbers in a given range. It populates an array with even numbers and then prints each element using “forEach”.
Example: To print all the even numbers in a range in JavaScript using forEach loop.
Javascript
// JavaScript program to print even // numbers in a given range using forEach loop let start = 4; let end = 15; let evenArray = []; for (let num = start; num <= end; num++) { if (num % 2 === 0) { evenArray.push(num); } } evenArray.forEach((evenNumber) => { console.log(evenNumber); }); |
Output
4 6 8 10 12 14
Time Complexity: O(n)
Space Complexity: O(n)
Print all Even Numbers in a Range in JavaScript Array
We have to find all even numbers within a given range. To solve this question we are given the range(start, end) in which we have to find the answer.
There are several ways to print all the even numbers in a range in an array using JavaScript which are as follows:
Table of Content
- Using for Loop in JavaScript
- Using While Loop in JavaScript
- Using forEach Loop in JavaScript