josh_c
josh_c

Reputation: 149

Javascript reduce keeps returning undefined

I'm trying to figure out a problem where I need to find the product of all numbers in an array.

For the life of me, I cannot figure out why this keeps returning undefined.

I would love any suggestions on why my code is not working. Thank you!

function mutliplyAllElements(arr) {

  arr.reduce(function(x, y) {
    return x * y;
  });
}

mutliplyAllElements([2, 3, 100]);  // 600

Upvotes: 2

Views: 1566

Answers (1)

Eddie
Eddie

Reputation: 26844

You are getting undefined because function mutliplyAllElements does not return anything. You have to return the value in the function.

function mutliplyAllElements(arr) {
  let val = arr.reduce(function(x, y) {
    return x * y;
  });
  return val;
}

console.log(mutliplyAllElements([2, 3, 100]));

Or you can make it shorter as:

function mutliplyAllElements(arr) {
  return arr.reduce((x, y) => x * y);
}

console.log( mutliplyAllElements([2, 3, 100]) );

Upvotes: 2

Related Questions