How to use forEach method In Javascript

The forEach method to go through each element of the array and by using the conditional statements, check if the element is odd and is within the ranges. If all the conditions are satisfied then the odd numbers are printed in the specific range.

Syntax:

array.forEach(function(currentValue, index, array) {
  // code
});

Example: The example uses the forEach method to print all odd numbers in a range of 1 to 50 in a JavaScript array.

Javascript
let arr = [2, 5, 1, 33, 55, 45, 34, 90, -12, -44];

let start = 1;
let end = 50;
arr.forEach((num) => {
  if (num >= start && num <= end && num % 2 !== 0) {
    console.log(num);
  }
});

Output
5
1
33
45

Print all Odd Numbers in a Range in JavaScript Array

Odd numbers are numbers that cannot be divided into equal parts. If we divide the odd number by 2, the remainder is 1. In JavaScript, if we want to print all Odd numbers in a range, we can print it by iterating over the array, applying the condition, and printing the odd numbers. There are various approaches to printing all odd numbers in a range in a JavaScript array which are as follows:

Table of Content

  • Using for Loop
  • Using forEach method
  • Using filter method
  • Using for…of Loop
  • Using recursion

Similar Reads

Using for Loop

The for loop is used to iterate over each element of the array and using the conditional block, check if the element satisfies the condition of odd numbers and also the range bound. If all the conditions are satisfied, then the odd numbers are printed using the console.log() function....

Using forEach method

The forEach method to go through each element of the array and by using the conditional statements, check if the element is odd and is within the ranges. If all the conditions are satisfied then the odd numbers are printed in the specific range....

Using filter method

The filter() method is used to create the array which consists of only the elements that satisfy the condition of odd elements along with the range bound. The new output array is printed as output....

Using for…of Loop

The for…of the loop is used to iterate through the array elements, and using the condition we are checking if the element is an odd number and is within the start and end range. If all the conditions are true, then we are printing the odd number as output....

Using recursion

In this approach we define a recursive function printOdd that takes start and end parameters. Inside the function, we check if the current number (start) is odd, If it is we log it to the console. If start is greater than end, we stop the recursion....