I'm having a competition with my friend, he told me to- Create a function called addThemAllTogether that takes in an array of numbers and returns the total of all of the items in the array added together.
What does that look like in Javascript?
I'm having a competition with my friend, he told me to- Create a function called addThemAllTogether that takes in an array of numbers and returns the total of all of the items in the array added together.
What does that look like in Javascript?
You don't, JavaScript already has that function, and it's called Array.prototype.reduce:
// set up some list of values
var list = [1,2,3,...,999,1000];
// run through the array, updating a tally value for every element we see:
var sum = list.reduce(function(runningTally, currentValue) {
// simplest possible thing: add the current value to the tally,
// which means at the end of the iteration the tally will the sum
// of all elements in the array.
return runningTally + currentValue;
}, 0)
The second argument "0" is the start value for the running tally. It's optional, but usually a good idea to explicitly set.
cycle through the array with a for loop
var array = [1,2,4,223,53,6,1];
var total = 0;
for( i = 0; i < array.length; i++ ) {
total += i;
}