order.amount
is a string, and if one of the operands of the + operator is a string, a concatenation is done instead of a sum.
You should convert it to number, for example using the unary plus operator:
var totalAmt = 0, i, order; // declaring the loop variables
for (var i in orders) {
order = orders[i];
if (order.status !='Cancelled')
totalAmt += +order.amount; // unary plus to convert to number
}
You could alternatively use:
totalAmt = totalAmt + (+order.amount);
totalAmt = totalAmt + Number(order.amount);
totalAmt = totalAmt + parseFloat(order.amount);
// etc...
Also you are using a for..in loop to iterate over orders
, if orders
is an array, you should use a normal for loop:
for (var i = 0; i<orders.length; i++) {
//...
}
That is because the for...in statement is intended to be used for iterate over object properties, for arrays it may be tempting to use it, because seems to work, but it's not recommended since it will iterate over the object properties, and if you have extended the Array.prototype, those properties will be also iterated in addition to the numeric indexes.
Another reason to avoid it is because the order of iteration used by this statement is arbitrary, and iterating over an array may not visit elements in numeric order, and also it seems to be much more slower than a simple for loop.
If iteration order is not important, I personally like iterating backwards:
var i = orders.length;
while (i--) {
//...
}