Beginner project: build a tip and bill splitter
Combine variables, functions, conditions, loops, arrays and objects into a working bill splitter, then connect it to a form.
In this lesson you will
- Plan a program before coding
- Build small functions and combine them
- Protect against bad input
- Connect your logic to a simple form
About 22 minutes
Your first real program
You have learned variables, operators, strings, conditions, loops, functions, arrays and objects. Those are the building blocks of nearly every program ever written. Now you will use them together to build something genuinely useful: a bill splitter. A group of friends finish dinner, the bill arrives, and someone has to work out the tip, add the tax, and divide it fairly. It is the kind of small, real problem programmers love to solve.
Step 1: understand the problem
Before writing any code, say what the program should do in plain words. This habit, called planning, saves hours.
- Input: the bill amount, the number of people, the tip percentage.
- Work: add the tip, add the total, divide by the number of people.
- Output: how much each person pays, shown as money with two decimals.
- Problem cases: zero or negative amounts, zero people.
Step 2: one small function at a time
function calculateTip(bill, tipPercent) {
return bill * (tipPercent / 100);
}
function splitBill(bill, tipPercent, people) {
const tip = calculateTip(bill, tipPercent);
const total = bill + tip;
return total / people;
}
console.log(splitBill(4000, 10, 4)); // 1100
We split the job into two functions. calculateTip does one thing. splitBill uses it. Each is easy to test on its own: if the tip on 4000 at 10 percent prints 400, you know that part works.
Test the core functions. Change the bill, tip and people, and check each answer with a calculator.
function calculateTip(bill, tipPercent) {
return bill * (tipPercent / 100);
}
function splitBill(bill, tipPercent, people) {
return (bill + calculateTip(bill, tipPercent)) / people;
}
console.log(splitBill(4000, 10, 4));
console.log(splitBill(2500, 15, 5));
Try your own numbers, such as splitBill(6000, 12, 3).
function calculateTip(bill, tipPercent) {
return bill * (tipPercent / 100);
}
function splitBill(bill, tipPercent, people) {
return (bill + calculateTip(bill, tipPercent)) / people;
}
console.log(splitBill(4000, 10, 4));
console.log(splitBill(2500, 15, 5));
console.log(splitBill(6000, 12, 3));
Step 3: protect against bad input
function safeSplit(bill, tipPercent, people) {
if (typeof bill !== "number" || bill <= 0) return "Enter a bill above zero";
if (people < 1 || !Number.isInteger(people)) return "People must be a whole number";
if (tipPercent < 0) return "Tip cannot be negative";
const perPerson = splitBill(bill, tipPercent, people);
return perPerson.toFixed(2);
}
Real users type strange things. Guard clauses check for trouble first and return a helpful message. The method toFixed(2) rounds a number to two decimal places and returns text, which is what we want for money.
Step 4: a nicer report with an object
function makeReceipt(bill, tipPercent, people) {
const tip = calculateTip(bill, tipPercent);
const total = bill + tip;
return {
bill,
tip,
total,
people,
each: total / people
};
}
const r = makeReceipt(4000, 10, 4);
console.log(`Bill: Rs ${r.bill}`);
console.log(`Tip: Rs ${r.tip}`);
console.log(`Total: Rs ${r.total}`);
console.log(`Each of ${r.people} pays Rs ${r.each.toFixed(2)}`);
Returning an object instead of a single number lets one function answer many questions. The short form { bill, tip } is a shortcut for { bill: bill, tip: tip } when the names match.
Step 5: compare several tip options with a loop
Print a small table showing what each person pays at 5, 10, 15 and 20 percent tips. Complete the loop.
const bill = 3000;
const people = 3;
const tips = [5, 10, 15, 20];
function each(bill, tipPercent, people) {
return (bill * (1 + tipPercent / 100)) / people;
}
// loop through tips and print one line each
for (const t of tips) { console.log(`${t}% tip: Rs ${each(bill, t, people).toFixed(2)}`); }
const bill = 3000;
const people = 3;
const tips = [5, 10, 15, 20];
function each(bill, tipPercent, people) {
return (bill * (1 + tipPercent / 100)) / people;
}
for (const t of tips) {
console.log(`${t}% tip: Rs ${each(bill, t, people).toFixed(2)}`);
}
Step 6: put it on a page
Everything so far prints to the console. The editor below connects the same logic to real form fields and a button. You will learn the page-changing commands (the DOM) in the next course module, so for now just read how the pieces fit together and try changing the numbers.
Type a bill, people and tip, then press the button. Change the tip rule so that a tip of 0 shows the message “No tip? That’s fine!” under the result.
<style>
body{font-family:Arial;padding:16px;max-width:320px}
input,button{padding:8px;margin:4px 0;width:100%;box-sizing:border-box;font-size:15px}
button{background:#5A28C8;color:#fff;border:0;border-radius:8px;font-weight:700}
#out{margin-top:10px;font-weight:700;color:#5A28C8}
</style>
<input id="bill" type="number" placeholder="Bill" value="3000">
<input id="people" type="number" placeholder="People" value="3">
<input id="tip" type="number" placeholder="Tip %" value="10">
<button id="go">Split it</button>
<div id="out"></div>
<script>
function each(b, t, n) { return (b * (1 + t / 100)) / n; }
document.getElementById('go').onclick = function () {
var b = Number(document.getElementById('bill').value);
var n = Number(document.getElementById('people').value);
var t = Number(document.getElementById('tip').value);
var out = document.getElementById('out');
if (b <= 0 || n < 1) { out.textContent = 'Check your numbers'; return; }
out.textContent = 'Each pays Rs ' + each(b, t, n).toFixed(2);
};
</script>
Inside the click function, after setting out.textContent, add an if (t === 0) that appends the message.
<style>
body{font-family:Arial;padding:16px;max-width:320px}
input,button{padding:8px;margin:4px 0;width:100%;box-sizing:border-box;font-size:15px}
button{background:#5A28C8;color:#fff;border:0;border-radius:8px;font-weight:700}
#out{margin-top:10px;font-weight:700;color:#5A28C8}
</style>
<input id="bill" type="number" placeholder="Bill" value="3000">
<input id="people" type="number" placeholder="People" value="3">
<input id="tip" type="number" placeholder="Tip %" value="10">
<button id="go">Split it</button>
<div id="out"></div>
<script>
function each(b, t, n) { return (b * (1 + t / 100)) / n; }
document.getElementById('go').onclick = function () {
var b = Number(document.getElementById('bill').value);
var n = Number(document.getElementById('people').value);
var t = Number(document.getElementById('tip').value);
var out = document.getElementById('out');
if (b <= 0 || n < 1) { out.textContent = 'Check your numbers'; return; }
out.textContent = 'Each pays Rs ' + each(b, t, n).toFixed(2);
if (t === 0) { out.textContent += ' (No tip? That is fine!)'; }
};
</script>
How to debug when it breaks
- Read the error: note the message and the line number.
- Print values: add
console.loglines to see what each variable holds. - Shrink the problem: test one function with simple numbers you can check by hand.
- Fix one thing at a time and run again.
- Explain it aloud: describing the code line by line to a friend (or a rubber duck) often reveals the mistake.
Ideas to extend your project
- Add a rounding option so everyone pays a round number.
- Let each person have a different share using an array of numbers.
- Add tax as a fourth input.
- Show a receipt as a list using a loop and template literals.
- Save the last result with
localStorage(coming later).
Trusting numbers typed into a page. They arrive as text. "10" + 5 gives "105". Convert with Number() first and check for NaN.
Variables, types, operators, conditions, loops, functions, arrays and objects: that is the heart of JavaScript. Everything that follows, from the DOM to APIs and frameworks, is built on exactly these pieces.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What should you do before writing code for a new program?
- Plan the input, work and output in plain words
- Start with colours
- Copy another project
- Skip testing
Planning saves time.
Why split code into small functions?
- They are easier to test and reuse
- They run faster
- It is required
- To hide errors
Each function does one thing.
What does (12.5).toFixed(2) return?
"12.50"12.512"12"
toFixed returns text with the given decimals.
Why convert form input with Number()?
- Input values are text
- It is faster
- Numbers are prettier
- It removes spaces only
Form values are strings.
Which is a good debugging step?
- Add console.log to see values
- Delete the file
- Ignore the error
- Rewrite everything
Printing values shows what is really happening.
Summary
- Plan input, work and output first.
- Small functions are easy to test.
- Guard clauses handle bad input.
- Debug by reading errors and printing values.
Questions
My project works in the console but not on the page. Why?
Check the element ids match, the script runs after the elements exist, and values are converted from text with Number().
How do I round to whole rupees?
Use Math.round(), Math.ceil() or Math.floor() depending on whether you want nearest, up or down.
What should I build next?
A to-do list, a quiz, or a unit converter. Each uses the same building blocks you just practised.
