Find and fix three bugs

“Squash the bugs”, a Green belt challenge from the CurlyScript Dojo. It uses what Summer School: Debugging: Becoming a Bug Detective teaches, and 3 tests check your answer.

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.

What the tests check

  • cartTotal([{ price: 10, qty: 2 }, { price: 5, qty: 1 }]) gives 25
  • cartTotal([{ price: 3, qty: 3 }]) gives 9
  • cartTotal([]) gives 0

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
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.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning