How to use For Loop In Javascript

In this method we will use the classic for loop to traverse the array and check if each element is odd or not and if it is odd then we will push only that element in the resulting oddNumbers Array. Here we again do the same and check if each element in the array is odd or not but we access the elements from their index in the array and we also use the “&&” conditions to only push the odd numbers in the new Array.

Example: Printing odd number in JavaScript using for loop.

Javascript
const arr = [1 , 2, 4, 9, 12, 13, 20];
const oddNumbers = []
for(let i = 0; i < arr.length; i++){
    arr[i] % 2 === 1 && oddNumbers.push(arr[i]);
}
console.log(oddNumbers);

Output
[ 1, 9, 13 ]

Print Odd Numbers in a JavaScript Array

JavaScript provides us with various approaches for printing odd numbers in an array. The core concept behind finding an odd number is based on the fundamental arithmetic property that odd numbers leave a remainder of 1 when divided by 2.

Table of Content

  • Using JavaScript Filter() Method
  • Using JavaScript ForEach() Method
  • Using JavaScript For Loop
  • Using JavaScript For…of Loop
  • Using Array.prototype.reduce

Similar Reads

Using JavaScript Filter() Method

JavaScript Array filter() Method is used to create a new array from a given array. The new array only consists of those elements which satisfy the conditions set by the argument function. Here we check whether each number when divided by 2 leaves a remainder of 1 to check if it is a odd number or not....

Using JavaScript ForEach() Method

The Array.forEach() method performs the operation on each element of the array. We can perform any operation on the each element of the given array. Here we again do the same and check if each element in the array is odd or not but we also use the “&&” conditions to only push the odd numbers in the new Array....

Using JavaScript For Loop

In this method we will use the classic for loop to traverse the array and check if each element is odd or not and if it is odd then we will push only that element in the resulting oddNumbers Array. Here we again do the same and check if each element in the array is odd or not but we access the elements from their index in the array and we also use the “&&” conditions to only push the odd numbers in the new Array....

Using JavaScript For…of Loop

This For…of Loop in JavaScript works in the same way as the for Loop where we can perform any operation on each element of the given array but it makes it easier as we don’t have to handle the index of the array to traverse the array....

Using Array.prototype.reduce

In this approach we will use reduce method which is used to accumulate values from an array into a single result. In this case it accumulates odd numbers from the array into a new array. For each element, it checks if it’s odd (not divisible by 2) and adds it to the accumulator array if it is....