JavaScript
Helper functions
Learn to break a big problem into small helper functions.
Helper functions
Instead of fitting a big problem into one function, you can split it into small helper functions. Each helper does a single job; the main function calls them to produce the result.
Example: to compute a price, you write two helpers named applyDiscount(price) and addTax(price). Then a finalPrice(price) function combines them with return addTax(applyDiscount(price)). Each step is now separate, readable and reusable.
Break into small pieces
A good helper function has a single responsibility: it either applies a discount, adds tax, or formats; not all at once. This is called the single responsibility principle.
As a result each function stays short and clear, bugs are easier to find, and you can reuse the helper elsewhere. For example you can call applyDiscount inside both finalPrice and cartTotal. This prevents code duplication.
Exercise Compute the price
Define two helper functions: applyDiscount(price) returns price * 0.9, addTax(price) returns price * 1.2. Then define a finalPrice(price) function: in its body write return addTax(applyDiscount(price)). Finally print the result with console.log(finalPrice(100)).
Show example solution
function applyDiscount(price) {
return price * 0.9;
}
function addTax(price) {
return price * 1.2;
}
function finalPrice(price) {
return addTax(applyDiscount(price));
}
console.log(finalPrice(100));
Test yourself
-
What is a helper function for?
- It slows the program down
- It splits a big problem into smaller pieces
- It allows you to declare variables
- It is used instead of a loop
Show answer
It splits a big problem into smaller pieces — Correct. Helper functions split a big problem into small, manageable pieces.
-
Call the helper function
function applyDiscount(price) {
return price * 0.9;
}
function finalPrice(price) {
return ____;
}
console.log(finalPrice(100));
Show answer
function applyDiscount(price) {
return price * 0.9;
}
function finalPrice(price) {
return applyDiscount(price);
}
console.log(finalPrice(100));
-
Helper function roles
- applyDiscount
- Applies a discount
- addTax
- Adds tax to the price
- formatPrice
- Formats the price as text
- finalPrice
- Combines the helpers
Next lesson: Summary - Parameters