Why functions exist
Yesterday's programs repeated the same calculation for every session: 20 * 3, then 15 * 2, then again for the next one. If the rule changes (say, add a five-minute break per session), you would have to find and fix every copy. A function gives a calculation a name, so you write it once and use it as many times as you like.
function totalMinutes(minutes, count) { // definition: keyword, name, parameters
return minutes * count; // body; return hands back the result
}
const total = totalMinutes(20, 3); // call: name plus arguments
console.log(total); // 60functionstarts a definition. Defining a function stores its instructions; nothing in the body runs yet.totalMinutesis its name.minutesandcountare parameters: names for the values the function will be given.- The body between the braces is the work.
returnsends a value back to whoever called the function, and ends the call.totalMinutes(20, 3)is a call. The values in the parentheses are arguments: during this callminutesis 20 andcountis 3.
Predict before running
Why do the two calls produce different results even though the function body is the same? Replace the numbers with variables after checking.
function totalMinutes(minutes, count) {
return minutes * count;
}
console.log(totalMinutes(20, 3));
console.log(totalMinutes(15, 2));Check your prediction
60
30Trace each statement in order. If your prediction differed, describe the first place your mental model and the result diverged before trying again.
Return is not print
A function can display a message and still return undefined. That is why you should decide what a caller receives before writing the body. In the example, noisy prints its calculation, but the outer log receives no returned result. Useful returns the number, allowing the caller to decide what to do with it.
Return also exits immediately. Code after an unconditional return inside the same path does not run. Avoid a newline directly after return when you intend to return a value: JavaScript may insert a semicolon and return undefined instead.
function noisy(value) {
console.log(value * 2);
}
function useful(value) {
return value * 2;
}
console.log(noisy(4));
console.log(useful(4) + 1);Check your prediction
8
undefined
9The first 8 is printed inside noisy; undefined is what its caller receives. useful produces a value that can participate in another calculation.
Parameters are local names, not magic inputs
Calling useful(4) binds value to 4 for that call. Calling it again with 10 creates another call with a different parameter value. A number argument does not become linked to the caller's variable. Passing an object, however, passes its reference; changing a property can affect the caller. Yesterday's reference model still applies.
Repair task: larger should give back the bigger of two numbers, but it logs it instead. Predict what the last line prints, run it, then repair the function.
function larger(a, b) {
if (a > b) {
console.log(a);
} else {
console.log(b);
}
}
console.log(larger(4, 9) + 1);Check your prediction
9
NaNlarger prints 9 but returns nothing, so the caller receives undefined, and undefined + 1 is NaN ("not a number").
One repair
function larger(a, b) {
if (a > b) {
return a;
}
return b;
}
console.log(larger(4, 9) + 1);
console.log(larger(9, 4) + 1);
console.log(larger(5, 5) + 1);10
10
6Each console.log became return, so the caller gets a number to add to. Testing both argument orders and two equal numbers checks every path through the if.
Before you move on
Defining a function only stores the instructions; calling it runs them. A function that returns a value lets the caller store it, compare it or print it, so keep console.log in the caller. Trace two calls with different arguments, one row per call.
Your turn
Defining Functions: practice
Write remainingMinutes(goal, completed). Return zero if completed is greater than the goal; otherwise return the difference. Print results for (60, 25) and (30, 45): 35 and 0.
// Define remainingMinutes before calling it.Hint 1: the idea
The result must never be negative.
Hint 2: a first step
Calculate the difference, then use an if branch for a negative value.
Show one solution
function remainingMinutes(goal, completed) {
const remaining = goal - completed;
if (remaining < 0) {
return 0;
}
return remaining;
}
console.log(remainingMinutes(60, 25));
console.log(remainingMinutes(30, 45));35
0Printing belongs outside the function. Test equality too: (30, 30) should return zero. Explain why a caller could use this return value in a webpage without changing the function.
What you should be able to explain
- Trace the three printed lines without treating log as return.
- Can a function return a number without printing anything?
- What tests would you write for a larger-of-two function?
Completion is saved in this browser only. It does not measure mastery.