3.1 Functions: Definition and Calls
SLO 2
Describe the principles of structured programming.
Decomposition starts here. Giving a block of steps a name and calling it by that name is what lets a program be built from parts instead of one long script, and the benefits section says plainly what you get: less repetition, one place to fix.
SLO 3
Describe, design, implement, and test structured programs using currently accepted methodology.
This section lays groundwork rather than completing the outcome — the functions here take no input and return nothing yet. What it does give you is the call-and-definition split every later design rests on: write it once, invoke it wherever it is needed.
Learning Objectives
By the end of this section you should be able to:
- Identify function calls in a program.
- Define a parameterless function that outputs strings.
- Describe benefits of using functions.
3.1.1 Calling a Function
You have been calling functions since your very first program. When you write console.log("Hello"), you are calling the log function. When you write Math.sqrt(16), you are calling the sqrt function. A function is a named, reusable block of code that performs a task when called.
Think of a function like a vending machine. You press a button (call the function), and the machine does its job and hands you a result. You do not need to know how the machine works inside. You just need to know which button to press.
When you call a function, the program pauses what it is doing, jumps to the function's code, runs it, and then comes back to the spot it left.
Figure 3.1.1 — Control jumps from the call into the function body and returns to the line right after the call.
You have been using functions like console.log() and prompt() since Chapter 1. We just have not used the word "function" formally until now. Every time you wrote console.log(something), you were calling a function.
▶ Press Run to see the output…
What you should see:
Area: 78.53981633974483
There are two function calls hiding in three lines. console.log(...) is one. The other is easy to miss: Math.PI is not a call. It is a stored value, a constant that lives on the built-in Math object. Math.sqrt(16) would be a call, because it does work and hands something back. The parentheses are the tell.
Math.PI is a value you read. Math.sqrt(16) is a job you order. A name on its own fetches; a name with parentheses after it runs.
1. Which line has a function call?
▶ Press Run to see the output…
- line 1
- line 2
- line 3
Solution
c. line 3 — console.log(offsetNum) is a function call. Lines 1 and 2 are assignment statements: they store a value, they do not run a job.
2. How many times is console.log() called?
▶ Press Run to see the output…
- 1
- 3
- 5
Solution
b. 3 — console.log() is called on lines 1, 4, and 5. The prompt() calls on lines 2 and 3 are function calls too, but the question asks specifically about console.log().
3. How many function calls are there in total?
▶ Press Run to see the output…
- 3
- 5
- 6
Solution
b. 5 — Number() twice, prompt() twice, and console.log() once. Five sets of parentheses, five calls.
Write a program that calls console.log() three times, each with a different message. Run it and watch the order the messages appear in.
Solution
▶ Press Run to see the output…
Output:
First message Second message Third message
They appear top to bottom, in call order. A program runs one statement at a time unless something tells it otherwise.
3.1.2 Defining a Function
Calling a function is only half the story. You can also define your own. In JavaScript you use the function keyword.
A function definition creates a new function. It has the function keyword, a name, parentheses, and a body wrapped in curly braces.
function functionName() {
// body statements
}
In JavaScript, { and } mark where the body starts and stops. Indenting is for humans. If you indent a line but leave it outside the braces, it is outside the function no matter how it looks.
The first line is the header. The code between the braces is the body. Everything in the body is indented one level, which the language does not require but every reader expects.
Definition 3.1.1 — A function definition creates a new function. It has the function keyword, a name, parentheses, and a body wrapped in curly braces.
▶ Press Run to see the output…
What you should see:
Welcome to the program! We hope you enjoy using it.
Here is what happens when JavaScript runs this:
- It reads the
functionline and stores the definition. It does not run the body yet. - It skips past the body and keeps reading.
- It reaches
printWelcome();— a call. It jumps back into the body. - It runs both
console.log()statements. - It returns to the line after the call. The program ends.
Notice the name: printWelcome, not print_welcome. JavaScript convention is camelCase — first word lowercase, each later word capitalized, no underscores. You saw this in Section 1.3 with variable names, and it applies to functions the same way.
This is where JavaScript differs from most languages you may meet later.
▶ Press Run to see the output…
What you should see:
Hello from a function defined below!
That works. Before running anything, JavaScript scans the whole file and registers every function declaration. By the time the first line executes, sayHello already exists. This scan-first behavior is called hoisting.
Do not lean on this. Hoisting is real, but code that calls things before defining them is harder to read, and it does not apply to every way of making a function — you will meet those in Section 3.2. Define first, call after. Knowing hoisting exists mostly helps you understand why a call that "should" have failed did not.
1. What is wrong with the first line of this function definition?
function waterPlant {
- The body should be indented.
- Parentheses should go after
waterPlant. functionshould befuncbeforewaterPlant.
Solution
b. Parentheses should go after waterPlant. The correct header is function waterPlant() {. The parentheses are required even when the function takes nothing.
2. What is the output?
▶ Press Run to see the output…
Phone: (864) 555-0199thenUser info:User info:thenPhone: (864) 555-0199User info:only — the function is never called
Solution
b. User info: prints first, then the call to printPhoneNum() runs its body and prints the phone line. Defining a function does not run it; only the call does.
3. Which statement calls a function named printPcSpecs?
printPcSpecsprintPcSpecs()function printPcSpecs()
Solution
b. printPcSpecs() — the parentheses make it a call. Option a just names the function without running it. Option c is the start of a definition, not a call.
4. Which is an appropriate name for a function that calculates a user's taxes?
calcTaxcalculate user taxcT
Solution
a. calcTax — descriptive, camelCase, no spaces. Option b has spaces, which are not allowed in a name. Option c is too short to tell a reader anything.
Define a function called greet that prints "Hello!" and "Nice to meet you!" on two lines. Then call it.
Solution
▶ Press Run to see the output…
Output:
Hello! Nice to meet you!
Take the code below and fix it. It has two problems.
function ShowTotal {
console.log("Total: 42")
}
Solution
Missing parentheses in the header, and the name should be camelCase rather than starting with a capital.
▶ Press Run to see the output…
A capitalized first letter is not a syntax error — JavaScript will run ShowTotal happily. It is a convention violation, and conventions are what let another reader guess right. Names starting with a capital are reserved for a kind of function you will meet in Chapter 5.
3.1.3 Benefits of Functions
Why bother writing functions at all? Three reasons.
- Modularity — A function groups the code for one task in one place. Instead of scattering ten lines of distance math through your program, you put it in
calcDistance(). - Reusability — Once defined, you can call a function as often as you like. Need a distance three times? Three calls, not three copies.
- Maintainability — If the way you calculate distance has to change, you change one body instead of hunting every copy. Code that is modular and reusable is also far easier for someone else to pick up.
You have been reusing other people's functions all along — console.log(), prompt(), Number(), Math.sqrt(). Writing your own is the step from being a user of code to being an author of it.
Before, with the math written out three times:
▶ Press Run to see the output…
After, with one function:
▶ Press Run to see the output…
What you should see:
Distance 1: 5 Distance 2: 5 Distance 3: 5
The second version is shorter, reads better, and if the formula ever changes — say to Math.hypot(x2 - x1, y2 - y1), which does the same job in one call — you edit one line.
This function takes four values in the parentheses. Those are parameters, and they are the whole subject of Section 3.2. For now, notice only what they bought you: one definition, three different results.
1. In the "before" version, how many lines mention a coordinate value? In the "after" version?
- 3 and 1
- 6 and 3
- 9 and 3
Solution
b. 6 and 3 — the "before" version spends two lines per distance (one declaring the four coordinates, one doing the math), so six in total. The "after" version passes the coordinates straight into the three calls, so three.
2. How many times can calcDistance() be called?
- once
- three times
- as many times as you like
Solution
c. as many times as you like. That is what reusability means — the definition sets no limit on the number of calls.
Write a function, concessions(), that prints the food and drink options at a cinema, then call it.
The output should be:
Food/Drink Options: Popcorn: $8-10 Candy: $3-5 Soft drink: $5-7
Solution
▶ Press Run to see the output…
Write a function, terms(), that asks the user to accept the terms and conditions, reads a Y or N, and prints a response. Then read in a number of users and call terms() once for each.
With 1 user answering Y:
Do you accept the terms and conditions? Thank you for accepting.
With 2 users answering N then Y:
Do you accept the terms and conditions? Have a good day. Do you accept the terms and conditions? Thank you for accepting.
Solution
▶ Press Run to see the output…
The loop calls one function repeatedly. Write the asking-and-answering once, run it as many times as there are users. That is modularity and reusability in four lines.
The program below prints a receipt header three times. Rewrite it so the header lives in one function that gets called three times, then check that the output is unchanged.
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…
Output is identical, which is the point — a refactor changes the code, not the behavior. The header text now appears once. Change it to === CORNER SHOP === and one edit updates all three receipts, where before you would have had to find and fix three copies and hope you caught them all.
Problem Set 3.1
3.1.1 Which line has a function call?
let inputNum = 14; let offsetNum = inputNum - 10; console.log(offsetNum);
- line 1
- line 2
- line 3
Solution
Step 1 — Recall what a function call looks like: A call is a name followed by parentheses, which means "run it now."
Step 2 — Check each line: Line 1 (let inputNum = 14;) is an assignment. Line 2 (let offsetNum = inputNum - 10;) is also an assignment with only arithmetic. Line 3, console.log(offsetNum);, has the name console.log followed by parentheses.
Answer: c. line 3
3.1.2 How many times is console.log() called?
console.log("Please log in");
let username = prompt("Username:");
let password = prompt("Password:");
console.log("Login successful");
console.log("Welcome,", username);
- 1
- 3
- 5
Solution
Step 1 — Scan for every console.log( occurrence: Line 1: console.log("Please log in") — yes. Lines 2 and 3 use prompt(), not console.log(). Line 4: console.log("Login successful") — yes. Line 5: console.log("Welcome,", username) — yes.
Step 2 — Count: That gives three calls to console.log() (the two prompt() calls are function calls too, but not of console.log()).
Answer: b. 3
3.1.3 How many function calls are there in total?
let width = Number(prompt("Enter width:"));
let height = Number(prompt("Enter height:"));
console.log("Area is", width * height);
- 3
- 5
- 6
Solution
Step 1 — Count calls line by line: Line 1: Number(...) and inside it prompt(...) — two calls. Line 2: Number(...) and prompt(...) again — two more calls. Line 3: console.log(...) — one call.
Step 2 — Total: \(2 + 2 + 1 = 5\) calls.
Answer: b. 5
3.1.4 What is wrong with the first line of this function definition?
function waterPlant {
- The body should be indented.
- Parentheses should go after
waterPlant. functionshould befuncbeforewaterPlant.
Solution
Step 1 — Compare against the definition format: A header must be function name() { — the keyword, then the name, then parentheses, then {.
Step 2 — Check each option: Option a is wrong because indentation is a convention, not required in the header. Option c is wrong because the keyword is function, not func. The missing piece in function waterPlant { is the empty pair of parentheses after the name.
Answer: b. Parentheses should go after waterPlant.
3.1.5 What is the output?
function printPhoneNum() {
console.log("Phone: (864) 555-0199");
}
console.log("User info:");
printPhoneNum();
Phone: (864) 555-0199thenUser info:User info:thenPhone: (864) 555-0199User info:only — the function is never called
Solution
Step 1 — Trace execution order: Statements run top to bottom. First, the function definition is stored but its body does not run yet. Then console.log("User info:") executes and prints User info:.
Step 2 — Run the call: Next, printPhoneNum(); jumps into the body and prints Phone: (864) 555-0199. So option c is wrong (the function is called), and option a has the order reversed.
Answer: b. User info: then Phone: (864) 555-0199
3.1.6 Which statement calls a function named printPcSpecs?
printPcSpecsprintPcSpecs()function printPcSpecs()
Solution
Step 1 — Apply the "parentheses mean run it" rule: Writing just printPcSpecs names the function without running it. Writing function printPcSpecs() starts a definition, not a call.
Step 2 — Identify the call: Only printPcSpecs() — name plus parentheses as a statement — actually invokes the function.
Answer: b. printPcSpecs()
3.1.7 Which is an appropriate name for a function that calculates a user's taxes?
calcTaxcalculate user taxcT
Solution
Step 1 — Check naming rules: A JavaScript identifier cannot contain spaces, so calculate user tax is invalid syntax.
Step 2 — Check readability and convention: cT is legal but tells a reader nothing. calcTax is descriptive, uses camelCase, has no spaces or underscores — exactly what conventions call for.
Answer: a. calcTax
3.1.8 In the "before" version of Example 3.1.4, how many lines mention a coordinate value? In the "after" version?
- 3 and 1
- 6 and 3
- 9 and 3
Solution
Step 1 — Count in the "before" version: Each of the three distances uses one line declaring four coordinate variables and one line doing the math with those coordinates — so 6 lines mention coordinate values (\(3 \times 2\)).
Step 2 — Count in the "after" version: Each distance is computed by passing coordinates directly into one calcDistance(...) call — 3 lines total.
Answer: b. 6 and 3
3.1.9 How many times can calcDistance() be called?
- once
- three times
- as many times as you like
Solution
Step 1 — Recall reusability: A function definition places no limit on how many times it can be invoked. Every call simply runs the same body again.
Step 2 — Evaluate the options: "Once" and "three times" would be arbitrary restrictions that don't exist in the language.
Answer: c. as many times as you like
3.1.10 Explain in one sentence why this program prints nothing, and fix it.
function showMenu() {
console.log("1. Start 2. Options 3. Quit");
}
Solution
Step 1 — Explain why nothing prints: Defining a function only stores its code — the body never runs until the function is called. This program defines showMenu() but never calls it, so no output appears.
Step 2 — Fix it: Add a call statement after the definition:
function showMenu() {
console.log("1. Start 2. Options 3. Quit");
}
showMenu();
Now the call showMenu(); makes the body execute and the menu prints.
Answer: The program prints nothing because showMenu() is defined but never called; adding the call showMenu(); fixes it.
3.1.11 Write a function, concessions(), that prints the food and drink options at a cinema. The output should be: Food/Drink Options: Popcorn: $8-10 Candy: $3-5 Soft drink: $5-7
Solution
Step 1 — Define the function: Create a parameterless function whose single job is printing the options line.
function concessions() {
console.log("Food/Drink Options: Popcorn: $8-10 Candy: $3-5 Soft drink: $5-7");
}
Step 2 — Call it: Without a call the body never runs, so add concessions(); after the definition.
concessions();
Output:
Food/Drink Options: Popcorn: $8-10 Candy: $3-5 Soft drink: $5-7
Answer: The complete program is the concessions() definition above followed by the call concessions();, which produces exactly the required output.
3.1.12 Write a function, terms(), that asks the user to accept the terms and conditions, reads a Y or N, and prints a response. Then read in a number of users and call terms() once for each.
Solution
Step 1 — Define the reusable part: Put the ask-and-respond logic in one function so it can be called once per user.
function terms() {
console.log("Do you accept the terms and conditions?");
const answer = prompt("Enter Y or N:");
if (answer === "Y") {
console.log("Thank you for accepting.");
} else {
console.log("Have a good day.");
}
}
Step 2 — Read the number of users and loop: Read a count with prompt() converted via Number(), then call terms() once per user in a loop.
const numUsers = Number(prompt("How many users?"));
for (let i = 0; i < numUsers; i++) {
terms();
}
Step 3 — Verify against the sample runs: With 1 user answering Y, the loop runs once and prints the question then "Thank you for accepting." With 2 users answering N then Y, the question/response pair appears twice, first with "Have a good day." then with "Thank you for accepting." Both match the expected output.
Answer: The program above writes the interaction once in terms() and calls it once per user in a loop, producing exactly the sample outputs shown.
Key Terms
function — A named, reusable block of code that performs a task when called.
function call — A statement that runs a function's body, written as the name followed by parentheses.
function definition — Code that creates a new function using the function keyword.
function header — The first line of a function definition (function name() {).
function body — The code between the curly braces of a function definition.
camelCase — The JavaScript naming convention: first word lowercase, later words capitalized, no underscores.
hoisting — JavaScript's scan of the file before running it, which registers function declarations so they can be called from earlier lines.
modularity — Organizing code into separate groups, each responsible for a single task.
reusability — The ability to use the same code many times without rewriting it.
maintainability — How easy it is to change code without introducing errors.