The challenge
cartTotal(items) should add up price × qty for every item. But Buggsy got to it first. Fix it so all the tests pass.
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
cartTotal([{ price: 10, qty: 2 }, { price: 5, qty: 1 }])gives25cartTotal([{ price: 3, qty: 3 }])gives9cartTotal([])gives0
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
What is undefined + 20? The total needs a starting value.
Hint 2
Arrays start at index 0, and the last index is length - 1.
Hint 3
A function without return gives back undefined.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function cartTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].price * items[i].qty;
}
return total;
}
Learn what you need
This exercise uses what Summer School: Debugging: Becoming a Bug Detective teaches. Read those notes first if any of it is new.