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.
Parameters and arguments
name,completed, andgoalare parameters in the function declaration."Alex",3, and5are arguments passed during the function call.
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.