Factorialize algorithm - solution tests well in increments, not as a whole

Here’s my solution to the factorialize algorthim:

function factorialize(num) {
  var myArray = [];
  for(i = 1; i < num + 1; i++){
  myArray.reduce(function(a,b){return a*b;});
  return myArray;


The section that creates the array tests fine when I console.log myArray. When I cut out the reduce method, it works fine when I substitute the array for the array name. For some reason, in my solution above, the reduce method will not pick up the values for myArray and returns undefined.

Any thoughts on why this is happening?

Reduce should return a single value.

Please go through https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

To fix your code, you should return the same of the accumulator and current value passed to the Reduce function

1 Like

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


1 Like

you are returning myArray - not the results of the reduce.

try this:

return myArray.reduce(function(a,b){return a*b;});


in hind site, I should have led you to the answer instead of giving it to you. my bad :frowning:

I’m not sure why you are getting undefined… it wasn’t undefined for me.

Yes, as Jason says.

The function reduce does not change the array, it returns a value. And as pointed out, you are returning that unchanged array instead of the value that reduce created (and assigned to nothing). You can either return it directly like Jason suggests or you can (if you want for clarity) assign it to a variable…

var answer = myArray.reduce(function(a,b){return a*b;});

… and return that.

Jason’s approach is probably more common with experienced coders, but sometimes beginners like things broken up and clearer.


Thanks! I thought reduce changed the array.

Thanks so much, I really appreciate the link.!