Syncing account progress…

Back

Beginner · 15 min

Project: a shopping receipt

Combine objects, arrays, loops, and functions in a small working program.

Calculate each line

A shopping basket can be an array of objects. A function calculates one line total, while a loop adds all the line totals.

function lineTotal(item) {
  return item.price * item.quantity;
}
const basket = [
  { name: "Pen", price: 2, quantity: 3 },
  { name: "Book", price: 5, quantity: 2 }
];
let total = 0;
for (const item of basket) {
  total += lineTotal(item);
}
console.log("Total: " + total);

Output

Total: 16

Format the receipt

toFixed(2) returns a string with two decimal places. Use it to format the final output. It does not make floating-point arithmetic exact; real payment systems need a deliberate money representation.

const total = 16;
console.log("Total: " + total.toFixed(2));

Output

Total: 16.00

Put it into practice

  1. Predict the output of each example before running it.
  2. Complete the coding task, then try the practice questions.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Finish the receipt

Fix lineTotal so it multiplies the price by the quantity. Keep the loop and display the exact receipt total.

Practice