How to return the product of odd numbers in JavaScript
To obtain the product of odd numbers in JavaScript, we can perform the following general steps:
Create a function specifically designed for this purpose.
Pass an array as an argument to the function, which will contain the numbers we want to process.
Invoke the function by calling it.
Within the function, implement the logic to calculate the product of the odd numbers in the array.
Finally, make sure to return the calculated product from the function.
By following these steps, we can calculate and retrieve the product of the odd numbers within the given array.
Let's write the code and understand how we can return the product of odd numbers.
Code example
Code explanation
Let's take a closer look at the code block provided above.
Line 1: Firstly, we define a function named
ProductofOddNumbers. We pass an array namednumarrin that function for getting integers as input.Line 2: We define a variable called
productand initialize it to the value1. Theproductvariable will store the product of odd numbers.Line 3: In order to iterate over every integer present in the array, we use a
forloop. An array starts from the 0th index, so our loop will start iteration from the 0th index and continue to iterate through the whole length of the array.Line 4: Inside the
forloop, we use anifcondition to check the nature of the integer to be even or odd. We then use the modulo operation (numarr[i] % 2 != 0), dividing each integer by 2 and comparing it with 0.Line 5: When an odd number is found, we'll multiply that number with the
productvariable.Line 8: As the loop continues its iteration, the
productvariable accumulates the multiplication of all the odd numbers encountered so far. After the loop finishes, the output stored in theproductvariable is returned.