JavaScript Basics: Make Web Pages Come Alive · Lesson 8 of 8

Lesson 8: Mini Project: A Tip and Marks Calculator

Build a small calculator page that uses variables, functions, conditions and events together, then plan what to learn next.

Lesson 8: Mini Project: A Tip and Marks Calculator

Let us build a marks calculator: type your marks in three subjects, click a button, and the page shows your total, percentage and grade.

Step 1: the logic first

Write and test the thinking as plain functions before touching the page.

function percentage(marks, fullMarks) {
  const total = marks.reduce((a, b) => a + b, 0);
  return (total / fullMarks) * 100;
}

function grade(p) {
  if (p >= 80) return "Distinction";
  if (p >= 60) return "First division";
  if (p >= 40) return "Pass";
  return "Fail";
}

const p = percentage([72, 85, 64], 300);
console.log(p.toFixed(1));
console.log(grade(p));

Output:

73.7
First division

Step 2: the page

<h2>Marks calculator</h2>
<input id="m1" type="number" placeholder="Subject 1 (out of 100)">
<input id="m2" type="number" placeholder="Subject 2 (out of 100)">
<input id="m3" type="number" placeholder="Subject 3 (out of 100)">
<button id="calc">Calculate</button>
<p id="result"></p>

<script>
  function percentage(marks, fullMarks) {
    const total = marks.reduce((a, b) => a + b, 0);
    return (total / fullMarks) * 100;
  }
  function grade(p) {
    if (p >= 80) return "Distinction";
    if (p >= 60) return "First division";
    if (p >= 40) return "Pass";
    return "Fail";
  }

  document.getElementById("calc").addEventListener("click", () => {
    const marks = ["m1", "m2", "m3"].map(id => Number(document.getElementById(id).value));
    const p = percentage(marks, 300);
    document.getElementById("result").textContent =
      `Percentage: ${p.toFixed(1)}% - ${grade(p)}`;
  });
</script>

Everything you learned is here: functions, an array and map, template strings, an event, and the DOM.

Make it better

  • Show a message if a box is empty or a mark is above 100.
  • Let the user choose the number of subjects.
  • Add some CSS to make it look good.

Where to go next

  • Learn CSS to style your pages and make them look professional.
  • Go deeper in JavaScript: objects and classes, promises and fetching data from the internet, modules.
  • Pick a path: front-end development (React or Vue), back-end development (Node.js), or mobile apps.
  • Build things. A personal website, a to-do list, a quiz app: finished small projects teach more than any lesson.

You finished the course. Pair it with our Python and AI courses to keep growing.

Finished this lesson?Log in to save your progress and pick up where you left off.
Back to the course

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 8: Mini Project: A Tip and Marks Calculator | MeroSir