// -----------------------------------
// Method #1
var sum = [1, 2, 3].reduce(add, 0);
function add(a, b) {
return a + b;
}
console.log(sum); // 6
// -----------------------------------
// Method #2
// ECMAScript 2015 (aka ECMAScript 6)
var sum = [1, 2, 3].reduce((a, b) => a + b, 0);
console.log(sum); // 6
// -----------------------------------
// Method #3
// Vanilla JS - slightly different syntactical approach
// Array.prototype.reduce can be used to iterate through the array, adding the current element value to the sum of the previous element values.
[1,2,3].reduce(function(acc, val) { return acc + val; });