Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How can I find the sum of an array of numbers in JavaScript?

I need to create a function that takes in an array of numbers an adds them up. I don't know JavaScript that well yet and am trying to do this by either using reduce or possibly by looping over all items. How would you do this?

2 Answers

JavaScript has a reduce function now (I don't think it was always that way). Try this:

function sum(numbers) {
  return numbers.reduce(function(a,b) {
    return a + b
  });
}

Keep in mind that this function has to take an array of values, otherwise it won't work.

Bonus points (if I could for) using reduce!

Just what I needed! Thanks, Oliver.