All JavaScript projects

JavaScript project

Weekly Expense Tracker

Record seven daily spending totals and compare your week's spending with a Rs 5,000 budget.

Step 2: Use the earlier basics, then add functions, arrays, and loops.

  • Variables
  • Data types
  • Operators
  • Conditions
  • Functions
  • Arrays
  • Loops

What you will build

  • Record one daily total at a time, starting with Day 1. Enter 0 for a day with no spending.
  • Show each day's spending, the total, and the average across recorded days.
  • Compare spending with a fixed weekly budget of Rs 5,000.
  • Undo the most recent day or start a new week. This practice version stores entries in memory, so refreshing clears them.

How to run this project

  1. Create a file named index.html in a new folder.
  2. Copy the complete code below into the file and save it.
  3. Open index.html in your browser. No installation or API key is needed.

Complete project code

This single file includes the HTML interface, basic CSS styling, and JavaScript behavior. The script runs after the HTML so all the elements are available.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Weekly Expense Tracker</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 640px; margin: 40px auto; padding: 0 20px; line-height: 1.6; }
    form { display: grid; gap: 12px; }
    input, select, button { font: inherit; padding: 8px; }
    button { cursor: pointer; }
    button:disabled { cursor: default; }
    li { margin: 12px 0; overflow-wrap: anywhere; }
    li button { margin-left: 12px; }
    input[type="checkbox"] { margin-right: 8px; }
    #answers { display: grid; gap: 8px; }
  </style>
</head>
<body>
<h1>Weekly Expense Tracker</h1>
<p>Weekly budget: Rs 5,000. Record up to seven daily totals.</p>
<form id="expense-form">
  <label for="amount">Daily spending (Rs, enter 0 for no spending)</label>
  <input id="amount" type="number" min="0" max="100000" step="0.01" required>
  <button id="add-day" type="submit">Add day</button>
</form>
<p id="message" role="status"></p>
<ol id="expense-list"></ol>
<p id="total"></p>
<p id="average"></p>
<p id="budget-status"></p>
<button id="undo" type="button" disabled>Undo last day</button>
<button id="reset" type="button" disabled>Start new week</button>
<script>
// 1. Keep the data separate from the page elements.
const dailyExpenses = [];
const weeklyBudgetPaise = 500000;
const daysInWeek = 7;

const form = document.querySelector("#expense-form");
const amountInput = document.querySelector("#amount");
const list = document.querySelector("#expense-list");
const message = document.querySelector("#message");
const addButton = document.querySelector("#add-day");
const undoButton = document.querySelector("#undo");
const resetButton = document.querySelector("#reset");

// 2. Give each function one clear job.
function formatMoney(paise) {
  return "Rs " + (paise / 100).toFixed(2);
}

function calculateTotal(expenses) {
  let total = 0;
  for (const amount of expenses) {
    total += amount;
  }
  return total;
}

function renderSummary() {
  list.replaceChildren();
  dailyExpenses.forEach((amount, index) => {
    const item = document.createElement("li");
    item.textContent = "Day " + (index + 1) + ": " + formatMoney(amount);
    list.append(item);
  });

  const total = calculateTotal(dailyExpenses);
  let average = 0;
  if (dailyExpenses.length > 0) {
    average = Math.round(total / dailyExpenses.length);
  }

  document.querySelector("#total").textContent = "Total spent: " + formatMoney(total);
  document.querySelector("#average").textContent = "Average per recorded day: " + formatMoney(average);

  const remaining = weeklyBudgetPaise - total;
  const budgetStatus = document.querySelector("#budget-status");
  if (remaining >= 0) {
    budgetStatus.textContent = "Budget remaining: " + formatMoney(remaining);
  } else {
    budgetStatus.textContent = "Over budget by: " + formatMoney(-remaining);
  }

  addButton.disabled = dailyExpenses.length >= daysInWeek;
  undoButton.disabled = dailyExpenses.length === 0;
  resetButton.disabled = dailyExpenses.length === 0;
}

// 3. Validate, update the array, then refresh the screen.
form.addEventListener("submit", (event) => {
  event.preventDefault();
  const amount = amountInput.valueAsNumber;

  if (dailyExpenses.length >= daysInWeek) {
    message.textContent = "This week is complete. Undo a day or start a new week.";
    return;
  }
  if (!Number.isFinite(amount) || amount < 0 || amount > 100000) {
    message.textContent = "Enter an amount from Rs 0 to Rs 100,000.";
    return;
  }

  dailyExpenses.push(Math.round(amount * 100));
  renderSummary();
  form.reset();
  amountInput.focus();
  message.textContent = "Recorded " + dailyExpenses.length + " of 7 days.";
});

undoButton.addEventListener("click", () => {
  dailyExpenses.pop();
  renderSummary();
  message.textContent = "Last day removed.";
  amountInput.focus();
});

resetButton.addEventListener("click", () => {
  dailyExpenses.length = 0;
  renderSummary();
  form.reset();
  message.textContent = "Ready for a new week.";
  amountInput.focus();
});

renderSummary();
</script>
</body>
</html>

How the code works

  1. 1. Build on variables, types, and conditions

    The weekly budget and day limit are numeric constants. Input validation uses number checks, comparison operators, and an early return, just like the first project. Each recorded amount is converted into whole paise before it enters the array. A zero amount is valid because a day without spending still counts.

  2. 2. Store one number per day in an array

    dailyExpenses starts as an empty array. push adds the next day's amount to the end; pop removes the last day. length tells us how many days are recorded. const prevents assigning a different array to dailyExpenses, but it still allows modifying that array's contents.

    JavaScript
    const dailyExpenses = [];
    dailyExpenses.push(12000); // Day 1: Rs 120
    dailyExpenses.push(8000);  // Day 2: Rs 80
    dailyExpenses.pop();       // Remove Day 2
  3. 3. Use parameters, a loop, and a return value

    calculateTotal receives an array through its expenses parameter. The for...of loop visits each number, and += adds it to a local total. return sends the sum to the calling code. The function reads its input without changing it or touching the page, making it easy to explain and reuse.

    JavaScript
    function calculateTotal(expenses) {
      let total = 0;
      for (const amount of expenses) {
        total += amount;
      }
      return total;
    }
  4. 4. Render the list and calculate an average

    forEach provides both the amount and its zero-based index. Adding 1 to the index produces the human-readable day number. renderSummary calculates the total once and divides by the recorded day count to find the average. Checking length > 0 prevents division by zero for an empty week. formatMoney handles rupee formatting in one place.

  5. 5. Show whether spending is within budget

    remaining is the budget minus the total. if...else chooses either a remaining-budget message or an overspending message. When remaining is negative, -remaining displays the overspend as a positive amount. Button disabled properties are booleans derived from the array length.

  6. 6. Keep changes and screen updates together

    Each event follows the same sequence: update the array, then call renderSummary. The submit handler checks the seven-day limit even if it is triggered with Enter. Undo reopens the seventh slot when needed, and reset sets the array length to zero. Data lives in this page session only; persistent storage can be a later extension.

Try it yourself

Enter 120, 80, and 0: the total is Rs 200, the average is Rs 66.67 across three days, and Rs 4,800 remains. Undo the zero day: the average becomes Rs 100. Add Rs 5,000 to see an overspend of Rs 200. Fill all seven days, check that an eighth cannot be added, then start a new week.

Back to all projects
Digital AI Academy

DevBrainBox Portal is proudly developed and managed by

Digital AI Academy
About the academy