JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 5: Functions and Reusable LogicLesson 25 of 150About 55 minutes

Lesson 25: Combining functions into applications

01Opening question

A tip calculator needs to read inputs, validate them, calculate, round and format. Should that be one long block of code or several small functions?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Three tiny functions, each with one job, combine into a complete calculation.

const toNumber = (text) => Number(text);
const tipFor = (bill, percent) => bill * percent / 100;
const money = (n) => `$${n.toFixed(2)}`;

const bill = toNumber("48");
console.log(money(tipFor(bill, 15)));

03Objective and prerequisites

Learning objective: Break a problem into small single-purpose functions, compose them so one function's output feeds the next, test each function, and assemble a small application.

You need: Lesson 22: Parameters and arguments, Lesson 23: Return values, Lesson 24: Arrow functions

Skills practised: Functions, Decomposition and composition, Application design.

04Explanation

Decomposition means splitting a problem into small steps and giving each step its own function: parse input, validate, calculate, format, display.

Small functions are easier to name, test and reuse. If a function's description needs the word "and", consider splitting it.

Composition means feeding one function's return value into the next: money(tipFor(toNumber(text), 15)). Store intermediate results in well-named variables when a chain gets long.

Test each function on its own with a few inputs before connecting them. When the full program misbehaves, you can then trust the pieces and look at how they are joined.

05Definitions

Decomposition
Breaking a problem into smaller parts, each solved by its own function.
Composition
Combining functions so the output of one becomes the input of the next.
Single responsibility
A function should have one clear job.
Helper function
A small function that supports a larger task.
Unit test
A check that one function returns the expected value for a given input.

Open the full glossary

06Visual learning object

Function call stack and return-value tracer. Trace a composed calculation and see each helper return its value to the next.

Loading the interactive object…

Open the full Function return-value visualizer page with its guided experiment.

07Examples

ex-025-01A small pipeline Browser-executable JavaScript

Each helper does one job; the main function connects them.

const parseAmount = (text) => Number(text.trim());
const addTip = (bill, percent) => bill + bill * percent / 100;
const formatMoney = (n) => `$${n.toFixed(2)}`;
function checkout(text, percent) {
  const bill = parseAmount(text);
  const total = addTip(bill, percent);
  return formatMoney(total);
}
console.log(checkout(" 40 ", 20));
Sample input
None
Expected output
$48.00
Common mistake
Doing parsing, maths and formatting in one long line that is hard to test.
Try this
Add a helper that rounds up to the next dollar.
Source
examples/ex-025-01-pipeline.js (repository pending publication)

ex-025-02Validation returns a result Browser-executable JavaScript

A validator returns an object instead of printing.

function validateBill(value) {
  if (Number.isNaN(value)) return { ok: false, error: "Enter a number" };
  if (value <= 0) return { ok: false, error: "Bill must be above 0" };
  return { ok: true, value };
}
console.log(validateBill(25).ok);
console.log(validateBill(-3).error);
console.log(validateBill(NaN).error);
Sample input
None
Expected output
true Bill must be above 0 Enter a number
Common mistake
Printing errors inside the validator so callers cannot reuse the message.
Try this
Add a rule for bills above 10000.
Source
examples/ex-025-02-validate.js (repository pending publication)

ex-025-03Testing each piece Browser-executable JavaScript

A tiny check function tests helpers one by one.

const splitBill = (total, people) => Math.ceil((total / people) * 100) / 100;
function check(label, actual, expected) {
  console.log(actual === expected ? "PASS" : "FAIL", label);
}
check("even split", splitBill(30, 3), 10);
check("rounds up", splitBill(10, 3), 3.34);
check("one person", splitBill(12.5, 1), 12.5);
Sample input
None
Expected output
PASS even split PASS rounds up PASS one person
Common mistake
Testing only through the final output, so a failure could come from any step.
Try this
Add a test for 0 people and decide what should happen.
Source
examples/ex-025-03-unit-tests.js (repository pending publication)

ex-025-04Configuration as a parameter Browser-executable JavaScript

Passing settings in makes functions reusable for other shops.

const config = { taxRate: 0.08, currency: "$" };
const withTax = (amount, cfg) => amount * (1 + cfg.taxRate);
const show = (amount, cfg) => `${cfg.currency}${amount.toFixed(2)}`;
console.log(show(withTax(50, config), config));
console.log(show(withTax(50, { taxRate: 0.2, currency: "€" }), { currency: "€" }));
Sample input
None
Expected output
$54.00 €60.00
Common mistake
Reading a global TAX constant inside every function.
Try this
Add a rounding setting to the config.
Source
examples/ex-025-04-config.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the pipeline order

Compose functions in the right order.

const parse = (text) => Number(text);
const double = (n) => n * 2;
const format = (n) => `$${n.toFixed(2)}`;
console.log(double(format(parse("7.5"))));

Split the bill

Write and connect two helpers.

// TODO: tipAmount(bill, percent) returns the tip
// TODO: perPerson(bill, percent, people) uses tipAmount and returns each share
console.log(perPerson(60, 15, 3).toFixed(2));

Mini tip calculator

Assemble an application from validated, tested functions.

const inputs = [
  { bill: "84", percent: "18", people: "4" },
  { bill: "abc", percent: "15", people: "2" },
  { bill: "50", percent: "20", people: "0" }
];

09Prediction

Commit to an answer first, then run the real code to compare.

const inc = (n) => n + 1;
const dbl = (n) => n * 2;
console.log(dbl(inc(3)), inc(dbl(3)));

What is printed?

10Debugging investigation

The tip is added twice

Each helper works on its own, but the combined calculator charges $60 on a $40 bill with a 25% tip.

const tipFor = (bill, percent) => bill * percent / 100;
const totalWithTip = (bill, percent) => bill + tipFor(bill, percent);
function checkout(bill, percent) {
  const tip = tipFor(bill, percent);
  const total = totalWithTip(bill, percent) + tip;
  return `Total: $${total.toFixed(2)}`;
}
const output = checkout(40, 25);
console.log(output);

More cases in the Debugging Detective Laboratory

11Practical scenario

From script to application

The Interactive Tip Calculator project uses exactly this structure: parse the form, validate, calculate, format and render. Each function is tested separately, so the interface code stays small.

const calc = (bill, pct) => ({ tip: bill * pct / 100 });
const fmt = (r) => `Tip $${r.tip.toFixed(2)}`;
console.log(fmt(calc(40, 15)));

12Knowledge check

1. What is printed?

const half = n => n / 2;
const add1 = n => n + 1;
console.log(add1(half(20)));
  • 11
  • 12
  • 10
  • 22

2. What is decomposition?

  • Deleting code
  • Splitting a problem into smaller functions
  • Running code faster
  • Combining files

3. Why is the result NaN?

const format = n => "$" + n.toFixed(2);
const triple = n => n * 3;
console.log(triple(format(2)));
  • format returns a string that is then multiplied
  • Number is wrong
  • Arrow functions cannot chain
  • toFixed is missing

4. Why test helper functions separately?

  • It is required by JavaScript
  • A failure points to one small piece
  • It makes code longer on purpose
  • It hides bugs

5. Which function has a single responsibility?

  • readFormCalculateAndShow
  • calculateTip
  • doEverything
  • handleAllTheThings

6. Where should console.log live in a well-structured program?

  • Inside every helper
  • At the edge, after the core functions return values
  • Nowhere
  • In validation only

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the pipeline order: Prints $15.00
  • Split the bill: Prints 23.00; tipAmount works; perPerson uses tipAmount
  • Mini tip calculator: Prints all three results; calculate is pure and correct; validate rejects zero people; Four helper functions
  • ex-025-01: output matches the documented expected output
  • ex-025-02: output matches the documented expected output
  • ex-025-03: output matches the documented expected output
  • ex-025-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-05-functions-and-reusable-logic/lesson-025-combining-functions-into-applications/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • Decompose: one small function per step.
  • Compose: pass return values from one function to the next.
  • Validate with result objects; print only at the edges.
  • Test each helper before connecting them.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation Decomposition
Context: I can write functions.
Task: Show me how to split a tip calculator into five small functions and explain each.
Constraints: Beginner level.
Expected behaviour: I can name the functions myself next time.
Testing: Give me another app to decompose.
Code prediction Composition drill
Context: I know how to combine functions.
Task: Give me five nested function calls and ask for the result.
Constraints: Wait for answers.
Expected behaviour: Include one where order changes the result.
Testing: Explain inside-out evaluation.
Debugging Pipeline bug
Context: My composed functions return NaN.
Task: Help me test each step to find where it breaks.
Constraints: No direct answer.
Expected behaviour: I find the step myself.
Testing: Suggest a test for each helper.
Exercise generation Mini applications
Context: I finished the mini tip calculator.
Task: Create one more mini application specification that needs parse, validate, calculate and format functions.
Constraints: Fictional data, exact output.
Expected behaviour: Include three inputs, one invalid.
Testing: Include expected output.
Code review Function design
Context: Here is my mini application.
Task: Review function names, responsibilities and where printing happens.
Constraints: Do not rewrite everything.
Expected behaviour: Each function has one job.
Testing: List the top three improvements.