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.
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