1

I'm new at javascript and am trying to finish up a test. So far I've done ok, but I can't seem to get right the three last things: - it should return the sum with one number array - it should return zero if all elements are zero - it should return the sum when passed array of numbers

const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10]; function sumNumbers(arr){ if (arr === undefined || arr.length == 0) { return 0; } array.reduce(function(a, b){ return a + b; }, 0); } 

2 Answers 2

1

You should return the result of reduce, there is no array named array, should be arr:

return arr.reduce(function(a, b){ 

const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10]; function sumNumbers(arr){ if (arr === undefined || arr.length == 0) { return 0; } return arr.reduce(function(a, b){ return a + b; }, 0); } console.log(sumNumbers(numbers));

Sign up to request clarification or add additional context in comments.

Comments

0

You need to return the result of return and take the same variable array.

function sumNumbers(array) { if (array === undefined || array.length == 0) { return 0; } return array.reduce(function(a, b) { return a + b; }, 0); } const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10]; console.log(sumNumbers(numbers));

A shorter approach uses a default array and return just the result of reduce.

function sumNumbers(array) { return (array || []).reduce(function(a, b) { return a + b; }, 0); } const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10]; console.log(sumNumbers(numbers));

1 Comment

Thanks a lot! I didn't see that.