Parameters, defaults, and return
How functions receive data, use fallbacks, and send results back.
Step 1
The idea
Functions have two sides: what goes in (parameters) and what comes out (return value).
Think of a vending machine. You put in money and a selection (parameters). Out comes a snack (return value). The machine does the work in between.
You've already used parameters. Now let's make functions that actually produce a value — not just print one.
Step 2
See it run
Full name: Priya Sharma
Test URL: https://staging.myapp.com/tests/42
Score: 85 — Grade: B
Formatted: [#001] Login Test// Function that returns a value
function fullName(first, last) {
return first + " " + last;
}
const name = fullName("Priya", "Sharma");
console.log("Full name:", name);
// Building a URL from parts
const buildUrl = (env, id) => `https://${env}.myapp.com/tests/${id}`;
console.log("Test URL:", buildUrl("staging", 42));
// Multiple return paths
function getGrade(score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
return "F";
}
const score = 85;
console.log(`Score: ${score} — Grade: ${getGrade(score)}`);
// Default parameter — used if caller doesn't provide one
function formatTestName(name, number = 1) {
return `[#${String(number).padStart(3, "0")}] ${name}`;
}
console.log("Formatted:", formatTestName("Login Test"));$ node params-return.jsStep 3
Now you try
Write a function called isValidEmail that:
- Takes a string as a parameter
- Returns
trueif the string contains an@symbol,falseotherwise - Hint:
string.includes("@")returns true if@is found
console.log(isValidEmail("priya@gmail.com")); // true
console.log(isValidEmail("not-an-email")); // falseconsole.log(isValid ? "OK" : "BAD") — no need to store it in a variable first.Step 4
Why a tester cares
Functions that return values let you build reusable tools. Here's a small data analysis library — three functions, each returning something useful:
function average(numbers) {
const total = numbers.reduce((sum, n) => sum + n, 0);
return total / numbers.length;
}
function highest(numbers) {
return Math.max(...numbers);
}
function summary(label, numbers) {
return {
label,
avg: average(numbers).toFixed(1),
best: highest(numbers),
passed: numbers.filter(n => n >= 60).length,
total: numbers.length,
};
}
const mathScores = [82, 91, 67, 54, 78];
const scienceScores = [74, 88, 95, 60, 70];
console.log(summary("Maths", mathScores));
console.log(summary("Science", scienceScores));$ node stats.jsEach function has a clear input (parameters) and a clear output (return value). That's what makes them composable — you can use average() inside summary() without rewriting the logic.
Recap
- 1return sends a value out of the function — the caller can store or use it.
- 2A function with no return statement produces undefined — not an error, just nothing.
- 3Default parameters (param = defaultValue) are used when the caller doesn't provide that argument.