# Total sum in a shopping calculator in JavaScript

Let's now make it so that the total sum of purchases is displayed below the table. There are nuances here.

If you think about the situation, it becomes clear that the sum should be adjusted not only when adding a new purchase, but also when deleting and editing.

I would suggest in this case to make some function, let's call it `recountTotal`, which will perform a full recalculation of the total sum. That is, it will loop through all purchases and sum up the contents of their `cost` column.

With such a function, we can call it anywhere where some change in the total is expected. Of course, it is a bit not optimal to calculate the total sum each time. But we get a significant simplification of the code.

Use the intended function when creating a new purchase:

`add.addEventListener('click', function() { let tr = document.createElement('tr'); createCell(tr, name.value, 'name'); createCell(tr, price.value, 'price'); createCell(tr, amount.value, 'amount'); createCell(tr, price.value * amount.value, 'cost'); createCell(tr, 'remove', 'remove'); table.appendChild(tr); recountTotal(); // recalculate the total });`

Here is a blank of the described function:

`function recountTotal() { let costs = table.querySelectorAll('.cost'); if (costs) { // find the total sum and write it down into #total } }`

Implement the `recountTotal` function I described.

← →
↑
en ru