By the end of this lesson
Write a reusable function with explicit inputs and a return value.
Before you start
- Node.js 24 with a terminal and plain-text editor; the browser-only lesson is labelled separately.
- Complete lesson 10 or be comfortable with its examples.
Three words to know
- Parameter
- A name in a function definition.
- Argument
- A value supplied in a call.
- Return value
- The result sent back to the caller.
1. Return data instead of printing inside every rule
A function body runs when called. return supplies a result to the caller; console.log writes a message. Keeping them separate makes the calculation usable in tests, a CLI and a browser. A function with no executed return statement returns undefined.
function countOpen(statuses) {
let total = 0;
for (const status of statuses) {
if (status === "open") total += 1;
}
return total;
}
console.log(countOpen(["open", "closed", "open"]));
What you should see · example output
2
2. Local state belongs to a call
total is local to each call. Avoid silently changing an unrelated outer variable when a parameter and a return value will do. A default parameter is useful when omission has a clear meaning.
function greeting(name = "learner") {
return `Hello, ${name}!`;
}
console.log(greeting());
console.log(greeting("Sam"));
What you should see · example output
Hello, learner! Hello, Sam!
3. State the assumptions
countOpen counts exact lowercase open values; it does not reject unsupported statuses. Decide whether a function validates external inputs or assumes its caller already did. A short comment stating this contract is more useful than a claim that the function handles all possible data.
YOUR TURN
A small check before you continue
Write double(number) returning twice its input. How can a caller check it without printing inside the function?
Show a suggested answer
Return number * 2 and compare double(3) with 6 in a test. The caller can decide whether to display the result.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
