# How can I calculate the total price of products in a cart using JavaScript?

I’m stuck on how to calculate the total amount and total price of my cart in this project. The task is to create a simple (beginners) e-commerce website where a customer should be able to click on a product and add it to their cart (with the name, amount and price displayed of the product, the amount and price should update correctly according to how many times a customer clicks on the button attached to the product).

And I can only use javascript (or html if necessary).

I have the website mostly working. Everything can be added to the cart and the cart keeps track of the amount and price for each product.

But I can’t figure out how to make it so when I press the buy button, below the cart, the total amount and total price of all the products added to the cart is displayed in a string beneath the cart.

I’ve tried searching online for answers but I can’t seem to figure it out.

Anything you can think of is greatly appreciated because at this point I’m completely clueless. And worth to note, I’m really new to javascript!

Here are my javascript code thus far:

```var products =
[
{
"name": "Aloe Vera",
"image": "bilder/severin-candrian-dgvFsLfIX9E-unsplash.jpg",
"origin": "NederlĂ€nderna",
"description": "LĂ€ttskĂ¶tt suckulent med tjocka grĂ¶na blad. En av vĂ€rldens Ă€ldsta lĂ€kevĂ€xkter. Trivs pĂ„ soliga platser. LĂ„t den torka ut mellan varje vattning.",
"height": "120cm",
"care": "Trivs ljust, men undvik direkt solljus. Vattna undertill och inte pĂ„ vĂ€xten, men lĂ„t jorden torka mellan varje vattning. Ge flytande nĂ€ring frĂ„n vĂ„r till hĂ¶st. Eventuell omplantering ska gĂ¶ras pĂ„ vĂ„ren.",
"price": 59
},
{
"image": "bilder/severin-candrian-8nONCr6eTeg-unsplash.jpg",
"origin": "Brasilien",
"description": "Fin och spĂ€nnande vĂ€xt med kontrastrika blad med grĂ¶nt mĂ¶nster och lila undersida pĂ„ bladen. Denna dekorativa planta passar perfekt i en kruka pĂ„ golvet eller pĂ„ en piedestal eller ett sidobord.",
"height": "65cm",
"care": "Ge den lite utrymme sĂ„ att bladen kan strĂ€cka ut sig vĂ€l bĂ„de uppĂ„t och Ă„t sidorna och skapa en grĂ¶n och harmonisk atmosfĂ€r i hemmet. Trivs i ljus och halvskugga, undvik direkt solljus. HĂ„ll jorden lĂ€tt fuktig. Gillar att bli duschad pĂ„ bladen.",
"price": 299
},
{
"name": "Lyktranka",
"image": "bilder/severin-candrian-xGpYDi-0348-unsplash.jpg",
"origin": "Sydafrika, Swaziland och Zimbabwe",
"description": "Ăven kĂ€nd som HjĂ€rtan pĂ„ trĂ„d. Lyktrankan Ă€r mycket lĂ€tt att skĂ¶ta och Ă€r en vacker hĂ€ngvĂ€xt med smĂ„ mĂ¶rkgrĂ¶na hjĂ€rtformade blad med ett silverskimrande mĂ¶nster. Plantan kan bli Ă¶ver en meter, vilket gĂ¶r den vĂ€l lĂ€mpad som hĂ€ngvĂ€xt eller i en hĂ¶g kruka.",
"height": "15 cm",
"care": "Trivs ljust, undvik direkt solljus. LĂ„t den torka lĂ€tt mellan vattningarna.",
"price": 79
}
];

let cart = {} ;

function initCart() {
for (let product of products) {
cart[product.name] = 0;
}
}

function renderCart() {
let tbody = document.querySelector("#cart > tbody");
tbody.innerHTML = "";
for (let product of products) {
let row = tbody.insertRow(-1);
let cellName = row.insertCell(-1);
let cellAmount = row.insertCell(-1);
let cellPrice = row.insertCell(-1);
let amount = cart[product.name];
cellName.textContent = product.name;
cellAmount.textContent = amount;
cellPrice.textContent = amount * product.price;
}
}

function increment(name) {
console.log("Name: " + name);
cart[name]++;
renderCart();
}

document.getElementById("totalCart").textContent = "Du har lagt till " + count + " st" + " produkter." + " " + "Vilket blir en summa pĂ„ " + total + " kr" +  "." ;
}

var count = countCart() ;
var total = totalCart() ;

function countCart() {
var totalCount = 0 ;
for (var i in cart) {
totalCount += cart[i].amount ;
}
}

function totalCart() {
var totalPrice = 0 ;
for (var i in cart) {
totalPrice += cart[i].price ;
}
}

function renderProducts() {
const template = `
<img>
<div class="p-template">
<div>
<span class="name"></span>
</div>
<div class="origin"></div>
<div class="height"></div>
<div class="care"></div>
<div class="description"></div>
<div class="price"></div>
<div>
<input class="button" value="LĂ€gg i varukorg" type="button"/>
</div>
</div>
`;
const container = document.querySelector("#products");
for (let product of products) {
let item = document.createElement("div");
item.innerHTML = template;
item.querySelector("img").src = product.image;
item.querySelector(".name").textContent = product.name;
item.querySelector(".origin").textContent = product.origin;
item.querySelector(".height").textContent = product.height;
item.querySelector(".care").textContent = product.care;
item.querySelector(".description").textContent = product.description;
item.querySelector(".price").textContent = product.price;
container.appendChild(item);
}
}

renderProducts();
initCart();
renderCart();
}
```

And my html:

```<body>
<h1>Varukorg</h1>
<div class="container">
<div class="row">
<table class="table" id="cart">
<tr>
<th>Produkt</th>
<th>Antal</th>
<th>Pris</th>
</tr>
<tbody id="table-body"></tbody>
</table>
<form>
</form>
<p id="totalCart"></p>
<h2>VĂ€xter</h2>
<div class="" id="products"></div>
</div>
</div>
</body>
<script src="inlamning2.js"></script>
```

Sorry some of the words are in Swedish! The only words you probably need to know is:

“lĂ€gg i varukorgen” = add to cart

“pris” = price

“antal” = amount

“produkt” = product

Your issue is that your `cart` is only storing the following information in key-value pairs: the key is the product name, and the quantity is the value. There is no price information in the `cart` object at all, therefore computing it requires looking up the original `products` array.

Moreover, `count` and `total` are declared outside the `buy()` function, yet the function, when invoked, does not update these values. These values are only set at runtime and is not updated after.

Therefore the quickest solution is to rewrite your `buy()` function into something like this, while removing the `countCart()` and `totalCart()` functions:

```function buy() {
var count = Object.values(cart).reduce((sum, cur) => sum += cur, 0);
var total = Object.entries(cart).reduce((sum, cur) => {
const [product, quantity] = cur;
return sum += products.find(p => p.name === product).price * quantity;
}, 0);

document.getElementById("totalCart").textContent = "Du har lagt till " + count + " st" + " produkter." + " " + "Vilket blir en summa pĂ„ " + total + " kr" + ".";
}
```

Explanation of the code:

1. `count` is pretty straight forward: you get all the values in your `cart` object and sum them up using `Array.prototype.reduce`
2. `total` is a bit complicated: you need to iterate through your `cart` in a way that gives you access to with the key (product name) and value (the quantity). Object.entries() can do that for you. Then it is a matter of looking up the `products` array of object to retrieve the price for a given product, and multiplying the quantity.

```var products = [{
"name": "Aloe Vera",
"image": "bilder/severin-candrian-dgvFsLfIX9E-unsplash.jpg",
"origin": "NederlĂ€nderna",
"description": "LĂ€ttskĂ¶tt suckulent med tjocka grĂ¶na blad. En av vĂ€rldens Ă€ldsta lĂ€kevĂ€xkter. Trivs pĂ„ soliga platser. LĂ„t den torka ut mellan varje vattning.",
"height": "120cm",
"care": "Trivs ljust, men undvik direkt solljus. Vattna undertill och inte pĂ„ vĂ€xten, men lĂ„t jorden torka mellan varje vattning. Ge flytande nĂ€ring frĂ„n vĂ„r till hĂ¶st. Eventuell omplantering ska gĂ¶ras pĂ„ vĂ„ren.",
"price": 59
},
{
"image": "bilder/severin-candrian-8nONCr6eTeg-unsplash.jpg",
"origin": "Brasilien",
"description": "Fin och spĂ€nnande vĂ€xt med kontrastrika blad med grĂ¶nt mĂ¶nster och lila undersida pĂ„ bladen. Denna dekorativa planta passar perfekt i en kruka pĂ„ golvet eller pĂ„ en piedestal eller ett sidobord.",
"height": "65cm",
"care": "Ge den lite utrymme sĂ„ att bladen kan strĂ€cka ut sig vĂ€l bĂ„de uppĂ„t och Ă„t sidorna och skapa en grĂ¶n och harmonisk atmosfĂ€r i hemmet. Trivs i ljus och halvskugga, undvik direkt solljus. HĂ„ll jorden lĂ€tt fuktig. Gillar att bli duschad pĂ„ bladen.",
"price": 299
},
{
"name": "Lyktranka",
"image": "bilder/severin-candrian-xGpYDi-0348-unsplash.jpg",
"origin": "Sydafrika, Swaziland och Zimbabwe",
"description": "Ăven kĂ€nd som HjĂ€rtan pĂ„ trĂ„d. Lyktrankan Ă€r mycket lĂ€tt att skĂ¶ta och Ă€r en vacker hĂ€ngvĂ€xt med smĂ„ mĂ¶rkgrĂ¶na hjĂ€rtformade blad med ett silverskimrande mĂ¶nster. Plantan kan bli Ă¶ver en meter, vilket gĂ¶r den vĂ€l lĂ€mpad som hĂ€ngvĂ€xt eller i en hĂ¶g kruka.",
"height": "15 cm",
"care": "Trivs ljust, undvik direkt solljus. LĂ„t den torka lĂ€tt mellan vattningarna.",
"price": 79
}
];

let cart = {};

function initCart() {
for (let product of products) {
cart[product.name] = 0;
}
}

function renderCart() {
let tbody = document.querySelector("#cart > tbody");
tbody.innerHTML = "";
for (let product of products) {
let row = tbody.insertRow(-1);
let cellName = row.insertCell(-1);
let cellAmount = row.insertCell(-1);
let cellPrice = row.insertCell(-1);
let amount = cart[product.name];
cellName.textContent = product.name;
cellAmount.textContent = amount;
cellPrice.textContent = amount * product.price;
}
}

function increment(name) {
console.log("Name: " + name);
cart[name]++;
renderCart();
}

var count = Object.values(cart).reduce((sum, cur) => sum += cur, 0);
var total = Object.entries(cart).reduce((sum, cur) => {
const [product, quantity] = cur;
return sum += products.find(p => p.name === product).price * quantity;
}, 0);

document.getElementById("totalCart").textContent = "Du har lagt till " + count + " st" + " produkter." + " " + "Vilket blir en summa pĂ„ " + total + " kr" + ".";
}

function renderProducts() {
const template = `
<img>
<div class="p-template">
<div>
<span class="name"></span>
</div>
<div class="origin"></div>
<div class="height"></div>
<div class="care"></div>
<div class="description"></div>
<div class="price"></div>
<div>
<input class="button" value="LĂ€gg i varukorg" type="button"/>
</div>
</div>
`;
const container = document.querySelector("#products");
for (let product of products) {
let item = document.createElement("div");
item.innerHTML = template;
item.querySelector("img").src = product.image;
item.querySelector(".name").textContent = product.name;
item.querySelector(".origin").textContent = product.origin;
item.querySelector(".height").textContent = product.height;
item.querySelector(".care").textContent = product.care;
item.querySelector(".description").textContent = product.description;
item.querySelector(".price").textContent = product.price;
container.appendChild(item);
}
}

renderProducts();
initCart();
renderCart();
}```
```<h1>Varukorg</h1>
<div class="container">
<div class="row">
<table class="table" id="cart">
<tr>
<th>Produkt</th>
<th>Antal</th>
<th>Pris</th>
</tr>