TypeScript
Add product
Learn to add products and update quantities.
Add-to-cart logic
The addToCart function adds a product to the cart. It first checks whether the product is already in the cart with find; if so, it increases the quantity; otherwise it adds a new item. This avoids creating duplicate entries when the same product is added multiple times.
function addToCart(cart: Cart, product: Product, quantity: number): Cart {
const existing = cart.items.find(i => i.product.id === product.id);
if (existing) {
existing.quantity += quantity;
} else {
cart.items.push({ product, quantity });
}
return cart;
}
Quantity update
When you find an existing item, you update its quantity. The += operator is the shortcut; you can also write existing.quantity = existing.quantity + quantity with the same meaning. Both are valid.
existing.quantity += quantity;
// equals: existing.quantity = existing.quantity + quantity;
To add a new item, you use cart.items.push({ product, quantity }).
Exercise Write the addToCart function
Define Product, CartItem, Cart interfaces. Write a function addToCart(cart: Cart, product: Product, quantity: number): Cart: if the product is already in the cart, increase its quantity; otherwise add a new item with cart.items.push. Add the same product twice and print the final quantity.
Show example solution
interface Product { id: string; name: string; price: number; }
interface CartItem { product: Product; quantity: number; }
interface Cart { items: CartItem[]; }
function addToCart(cart: Cart, product: Product, quantity: number): Cart {
const existing = cart.items.find(i => i.product.id === product.id);
if (existing) {
existing.quantity += quantity;
return cart;
}
cart.items.push({ product, quantity });
return cart;
}
const cart: Cart = { items: [] };
const apple: Product = { id: "a1", name: "Elma", price: 5 };
addToCart(cart, apple, 2);
addToCart(cart, apple, 3);
console.log(cart.items[0].quantity);
Test yourself
-
What should you do if the same product is already in the cart?
- Add the product a second time
- Delete the old item
- Throw an error
- Increase the quantity
Show answer
Increase the quantity — If the same product is already in the cart, you should increase the quantity of the existing item rather than adding a new one. This prevents duplicates.
-
Complete the find condition
const existing = cart.items.find(i => i.product.id === ____);
Show answer
const existing = cart.items.find(i => i.product.id === product.id);
-
Add-to-cart parts
- cart.items.find(...)
- Find existing item
- existing.quantity += quantity
- Increase quantity
- cart.items.push(...)
- Add a new item
- addToCart
- Adds a product to the cart
Next lesson: Total calculation