Reduce method does not work

Why is my solution not working
I used the reduce method here and i feel it should work can anyone help me out with this.
The problem
Return the factorial of the provided integer.

If the integer is represented with the letter n , a factorial is the product of all positive integers less than or equal to n .

Factorials are often represented with the shorthand notation n!

For example: 5! = 1 * 2 * 3 * 4 * 5 = 120

Only integers greater than or equal to zero will be supplied to the function.

   **This is the code I have written**

function factorialize(num) {
 let ourArray = []
 for (let i = 1; i <= num ; i++)
 {
   ourArray.push(i)
 }
 let product = 0
if(num === 0){
   product = 1;
}else{
   product = ourArray.reduce((num1,num2)=>{
     return num1 * num2;
 });
}
  return product 
}

console.log(factorialize(5));




   

Challenge: Factorialize a Number

Link to the challenge:

What does your factorialize function return?

The product of all the numbers smaller than the number provided

At least that is what i wanted it to return
currently it returns undefined

Why does it return undefined instead of the product of all numbers?

it returns …undefined

Have you told it to return the product?

Yes on line 8
num1 * num2

Is that the return value for the factorialize function?

yes it is, if you click the link and paste my solution there you will see undefined on the console

That is because there is currently no explicit return from the factorialize function. Have you tried returning the product?

Let me try it out give me a moment

it is the same result undefined

Please share your updated code, if you don’t mind.

You’ve made a variable named product, but what do you plan to do with that variable?

I have updated the code

I wanted to return the product of the numbers that “product” variable

Which you’re now doing, good! What’s the error now?

The problem that i have linked

no error it is not returning the desired value

ohh ok let me do that tryin to change the callback

It is my first day so i have reached my max number of replies :frowning:

most of the things seems to work but the last test factorialize(0) doesn’t work

I added an else statement and it works !!!

Thanks for the instant help It works now and i have edited the code

Well, it looks like you’ve changed your reduce callback as well. product used to hold the product in your previous implementation, you should change that back.

I think you’re confused about how the callback works, but you have two functions, and therefore need two returns.

1 Like
ourArray.reduce((num1,num2)=>{
    num1 * num2;
 });

You’re not returning anything from the callback, so this reduces to undefined. So product gets set to undefined.