JavaScript Functions for Beginners
A function groups instructions under a name so you can run the same task whenever you need it. In this example, you will create a reusable function that calculates coding progress and returns a message.
Start with the JavaScript explanation on Playcode123.com, then test variations in the Sandbox.
Your first function
function showWelcomeMessage() {
console.log("Welcome to JavaScript practice!");
}
showWelcomeMessage();
The function declaration stores the instructions. The final line calls the function, which makes those instructions run.
Functions with parameters
Parameters are names for values a function receives. They make one function useful for different data.
function createProgressMessage(name, completed, goal) {
return name + " completed " + completed + " of " + goal + " lessons.";
}
const message = createProgressMessage("Alex", 3, 5);
console.log(message);
return sends a value back to the code that called the function.
Build a reusable progress checker
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Functions</title>
</head>
<body>
<h1>Progress checker</h1>
<button id="checkButton">Check progress</button>
<p id="output"></p>
<script>
function createProgressMessage(name, completed, goal) {
const remaining = goal - completed;
return name + " has " + remaining + " lessons left.";
}
const button = document.getElementById("checkButton");
const output = document.getElementById("output");
button.addEventListener("click", function () {
output.textContent = createProgressMessage("Alex", 3, 5);
});
</script>
</body>
</html>
Expected result
When you click the button, the page displays: Alex has 2 lessons left. The event listener calls the function and uses its returned value.
Trace one click from input to output
- The click listener calls
createProgressMessage("Alex", 3, 5). In this call,namereceives “Alex”,completedreceives 3, andgoalreceives 5. - The function calculates
5 - 3and stores 2 in its localremainingvariable. returnsends the string “Alex has 2 lessons left.” back to the listener. It does not put anything on the page by itself.- The listener assigns that returned string to
output.textContent, which updates the paragraph.
Before a click, the output paragraph is empty. Another click repeats the same calculation because the arguments are fixed. To compare learners, change the call to createProgressMessage("Sam", 1, 4): the result should become “Sam has 3 lessons left.” You reuse the function without rewriting its calculation.
Parameters and arguments
name,completed, andgoalare parameters in the function declaration."Alex",3, and5are arguments passed during the function call.
Debug a result that appears only in Console
In a practice copy of the progress checker, replace the function’s return statement with console.log(name + " has " + remaining + " lessons left.");. Click Check progress. Console displays the correct sentence, but the function no longer returns that sentence to the listener.
A function that reaches its end without returning a value returns undefined. To see the difference directly, temporarily replace the statement inside the click listener with:
const result = createProgressMessage("Alex", 3, 5);
console.log("Returned value:", result);
output.textContent = result;
The first log comes from inside the function; the “Returned value” log shows undefined. Fix the function by restoring return name + " has " + remaining + " lessons left.";. The returned value should now be the sentence, and the page should display it. Remove the temporary logs after checking.
Use developer tools for the page running your example. In a sandbox, select the preview frame’s console context, or save the full HTML example and open it in a separate browser tab.
Common mistakes
- Defining but not calling: a function does nothing until it is called.
- Missing parentheses: use
createProgressMessage(...)to call it. - Confusing return and console.log:
returngives a value back;console.logonly displays a value in the console. - Using variables outside their scope: a variable declared inside a function normally exists only inside it.
- Passing arguments in the wrong order: the first argument is assigned to the first parameter.
- Using the returned value too late: code after
returninside the same function does not run.
Exercise
Change the function so it returns one message when the goal is complete and another when lessons remain. Test it with 3, 5 and with 5, 5. As an extra challenge, reject a completed value that is greater than the goal.
Check your work: call the function with several arguments and inspect both the page and browser console for errors.
Worked solution: give feedback for three outcomes
Try the exercise first. Then replace only the createProgressMessage function in the complete progress checker with this version. Keep the existing button, output paragraph, and click listener.
function createProgressMessage(name, completed, goal) {
if (completed > goal) {
return "Check your numbers: completed lessons exceed the goal.";
}
if (completed === goal) {
return name + " reached the goal of " + goal + " lessons!";
}
const remaining = goal - completed;
return name + " has " + remaining + " lessons left.";
}
The first condition handles a completed count above the goal, so you do not show a negative number of lessons remaining. The second checks an exact match with ===. Each return ends this function call immediately. Only an unfinished, within-goal count reaches the subtraction at the bottom.
This exercise assumes that completed and goal are non-negative whole numbers supplied by your code. It is not a complete validator for form input, missing values, negative numbers, or decimals.
Test the boundaries, not just the happy path
Change the function call inside the click listener to each of the following, save or run, and click Check progress:
createProgressMessage("Alex", 3, 5)→ “Alex has 2 lessons left.”createProgressMessage("Alex", 5, 5)→ “Alex reached the goal of 5 lessons!”createProgressMessage("Alex", 6, 5)→ “Check your numbers: completed lessons exceed the goal.”createProgressMessage("Sam", 0, 4)→ “Sam has 4 lessons left.”
Make one change yourself: add a special message when exactly one lesson remains. Put the new check after the subtraction and before the final return. For example, if (remaining === 1) { return name + " has 1 lesson left."; }. Test with 4 completed out of 5, then repeat the other cases to check that you kept their behaviour.
For keyboard use, add type="button" to the button and aria-live="polite" to the output paragraph. Next, revisit variables to understand the inputs, or extend the conditional quiz with a named function.
