Array elements are strings
, in order to properly add them, they have to be casted to integer
:
var sum = tot.reduce(function(a, b) {
return parseFloat(a) + parseFloat(b);
}, 0);
Taken from MDN:
the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
The is a common issue caused by +
operator used for both string concatenation and addition. Issue is best described with following example:
var result = '1' + 3 + 3 + 7 //result is '1337'
Edit: @Pointy - Nice catch, thanks! :)