Computing the subtotal of all items on their property criteria: qty * price I have an array which represent the item purchases of a customer, and computed the items subtotal in this logic:

function getSubtotal(arr) {
  let total = 0.00;
  arr.forEach(function(i) {
    total += (i.qty * i.price)
  });
  return total;  // 1274.21
}


And yes of course I get the correct result, but is there any efficient way to do this in JavaScript?



let data = [
  {
    name : 'Item 1', qty: 2, price: 15.50 // 31
  },
  {
    name : 'Item 2', qty: 17, price: 25.13 // 427.21
  }, 
  {
    name : 'Item 3', qty: 102, price: 8.00 // 816
  }
];

function getSubtotal(arr) {
  let total = 0.00;
  arr.forEach(function(i) {
    total += (i.qty * i.price)
  });
  return total; // 1274.21
}

document.write(getSubtotal(data));
You are computing the sum of an array, with a twist. Use Array.reduce() to compute sums.

Furthermore, if you are going to use the ECMAScript let language feature, you should also use arrow function notation.

function subtotal(items) {
    return items.reduce(
        ((total, item) =&gt; total + item.qty * item.price),
        0.00
    );
}


Better naming would help. "Get" implies that you are retrieving something that already exists, which is not the case here.  Also, i has a connotation of being an index counter, which makes its use in your forEach() confusing.