Alexey Tseitlin
Alexey Tseitlin

Reputation: 1309

javascript reduce gets undefined

I am getting undefined. The code works without the function. What am I doing wrong?

var myArr = [ 1, 2, 3, 4, 5 ];

function getSums(arr) {
  arr.reduce(a => a+1, 0);
}

document.write(getSums(myArr));

Upvotes: 0

Views: 2482

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

Three issues:

  1. When using reduce, you use the first two arguments (at least): The accumulator, and the current entry. (It has other arguments as well, but the first two are the ones used most often.)

  2. Your logic was just doing a + 1, which isn't adding values from the array together, it's adding 1 to the value for that entry.

  3. You need to return the value returned by reduce from your getSums function.

So:

var myArr = [ 1, 2, 3, 4, 5 ];

function getSums(arr) {
  return arr.reduce((sum, a) => sum + a, 0);
//^^^^^^            ^^^^   ^    ^^^^^^
}

console.log(getSums(myArr));

Or you could define getSums using arrow syntax, and then the return would be implied if you use a concise function body:

var myArr = [ 1, 2, 3, 4, 5 ];

let getSums = arr => arr.reduce((sum, a) => sum + a, 0);

console.log(getSums(myArr));

Upvotes: 4

Related Questions