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