JavaScript · 3 minute lesson
A function groups instructions under a name. Parameters describe the inputs it accepts, and a return statement provides a result to its caller. This lets you solve one small problem once and reuse the solution wherever the application needs it.
Good beginner functions do one clear job. For example, a progress calculator can accept completed lessons and a total, then return a percentage. Keep display code separate from the calculation so the same result can appear in a card, progress bar, or report.
Think about edge cases before using a function. What should happen when a course has no lessons? What if an argument is missing? An explicit decision is easier to maintain than accidental behavior. Test a normal input and a boundary case in the console before connecting the function to the interface.
Try the example
function progressPercent(completed, total) {
if (total <= 0) return 0;
return Math.round((completed / total) * 100);
}
console.log(progressPercent(3, 5)); // 60
console.log(progressPercent(0, 0)); // 0Practice
Write a function that returns a friendly greeting from a learner name. Then add a second function that calculates remaining lessons. Try each function with at least two different inputs and inspect its returned value.
Continue learning: Official documentation.