Functions
Give a reusable piece of work a name.
Inputs and outputs
A function groups work you can run again. Parameters name its inputs. The return statement supplies its output and exits the function. Calling a function runs it with the arguments you provide.
Keep the job small
A function that does one clear job is easier to understand and test. This example formats a label from a lesson title and a duration. It returns text without changing the page itself.
Use the result
The calling code decides what to do with the returned value. Here it places the label in a paragraph. Try calling the same function with a second pair of arguments.
Try the example
<h1>One small function.</h1>
<p id="label"></p>
<script>
function lessonLabel(title, minutes) {
return `${title} / ${minutes} min`;
}
const label = lessonLabel("Your first page", 5);
document.querySelector("#label").textContent = label;
</script>Enable JavaScript to edit and run the example in the playground.
Your turn
Change the function arguments. Add another paragraph and populate it with a second call.
Check your understanding
What does return do?
- Repeats the function
- Supplies an output and exits the function
- Adds a paragraph
Show answer and explanation
Supplies an output and exits the function. return ends the function execution and gives a value back to its caller.