Web Development Pro | Lesson 023 | Functions, Parameters, and Scope
Web Development Pro · Lesson 23 of 60
Module 3: JavaScript foundations
In this lesson
Prerequisites and learning outcomes
Complete lesson 22 first. This lesson builds on function contracts and local values. By the end, you can extract reusable pure calculations with explicit inputs and returns. Plan 10–15 minutes for the core explanation and additional time for the worked practice.
Give a calculation a clear contract
The workshop page will need the same seat-message logic in several places. Copying it into every event handler would make changes error-prone. A function packages a task behind named inputs and a result. The useful abstraction is not merely fewer lines; it is a clear agreement about what the function receives, what it returns, and what effects it may have.
Start with a pure function: for the same valid inputs it returns the same result and does not change external state. Pure functions are easy to test because they do not depend on a browser page, current time, or hidden variables. Not every function in a website is pure, but separating calculations from interface effects makes both easier to understand.
Distinguish parameters from arguments
Parameters are names in the function definition. Arguments are values supplied at a call. Return ends the function's current execution and gives a value back to the caller. Console.log displays a debugging message; it does not replace returning a result that another function can use.
function remainingSeats(capacity, reserved) {
return capacity - reserved;
}
function seatMessage(remaining) {
if (remaining === 0) return 'No seats remain.';
if (remaining === 1) return '1 seat remains.';
return `${remaining} seats remain.`;
}
const remaining = remainingSeats(12, 8);
const message = seatMessage(remaining);
console.log(remaining);
console.log(message);
For this first function, the contract requires nonnegative integer counts with reserved no greater than capacity. Those assumptions keep the arithmetic focused. A function does not enforce a written precondition automatically; callers or a later validated boundary must ensure it. Do not silently pass negative counts and assume the name makes them safe.
The second function receives the calculated count and formats a sentence. Keeping arithmetic and wording separate allows you to test them independently or change the wording without touching the seat calculation. This is a small example of separation by responsibility, not a demand to split every one-line expression into its own file.
Understand scope
A function's parameters and local declarations belong to its local scope. They do not automatically overwrite similarly named variables outside the function. Let and const are block-scoped, so a value declared inside an if block is not normally available after the block ends. Scope limits where names can be used and reduces accidental interference.
Avoid making a calculation depend on a mutable global variable when an argument would make the dependency explicit. If remainingSeats secretly reads a global reservedSeats, a test can change behavior without changing the function call. Passing reserved as an argument makes the source of the result visible at the call site.
A local variable can shadow an outer name, meaning the local name is the one resolved in that scope. Shadowing is legal, but overly similar names can confuse readers. Choose descriptive names and avoid reusing one generic name such as data for several different concepts in nested scopes.
Return deliberately on every intended path
A function without an explicit returned value produces undefined. That can be correct for an effect-only function, but it is usually a bug in a calculation expected to produce a number or string. Review every branch to ensure the contract is met. An early return can simplify a special case without nesting the rest of the function deeply.
Do not place a line break immediately after return when you intend to return an expression on the next line. JavaScript's automatic semicolon insertion can end the return statement, producing undefined instead. Keep the returned expression on the same line or use clearly parenthesized multiline expressions.
Function declarations and arrow functions are both useful. An arrow such as const double = value => value * 2 returns its expression implicitly. With a block body, braces require an explicit return for a value. Learn the difference before compressing every function into a short arrow expression. Readability matters more than minimizing punctuation.
Compose small pieces and test them
Composition means passing one function's result into another. The example first calculates remaining, then formats it. Keeping an intermediate variable makes debugging easy because you can inspect the numeric result separately from the sentence. Once the relationship is clear, a nested call can be acceptable, but it is not inherently more professional.
Test zero, one, and several seats because they select different wording branches. Test the arithmetic with a full workshop and an empty one within the stated contract. Do not use random inputs as a substitute for deliberate boundaries. A small set of meaningful cases often reveals more than many unexplained numbers.
The supplied Node tests call the exact defined functions inside an isolated context and compare their outputs. They also confirm that the original input variables remain unchanged. This proves the fixture's calculation behavior under those cases; it does not validate every possible invalid input or a real reservation workflow.
Worked practice
Worked exercise 1: Separate output from logging
Task: A function logs capacity - reserved but returns nothing, and the caller receives undefined. Worked answer: return the subtraction result, then log it at the call site if debugging output is needed. Returning supplies a value to the program; logging only displays a message.
Worked exercise 2: Cover wording branches
Task: Test seatMessage. Worked answer: check 0 gives “No seats remain,” 1 gives “1 seat remains,” and 4 gives “4 seats remain.” These cases cover the special cases and ordinary branch, including singular wording that a single large-number test would miss.
Worked exercise 3: Remove a hidden dependency
Task: remainingSeats reads a global reservedSeats. Worked answer: add a reserved parameter and pass the relevant count explicitly at each call. The function's behavior is now determined by its visible inputs, making reuse and tests more predictable.
Knowledge check
Question 1
What is an argument? A) A value supplied when calling a function. B) Only a name in its definition. C) A value returned after the function finishes. D) The function name used at the call site.
Check question 1: answer and explanation
Answer: A. Parameters name inputs; arguments provide values for a particular call.
Question 2
What does a function without a returned value produce? A) Zero automatically. B) An empty string automatically. C) undefined. D) Its last console message.
Check question 2: answer and explanation
Answer: C. Logging does not create an implicit return value.
Question 3
Why pass a dependency as a parameter? A) To stop the caller from supplying an invalid value. B) To make the input relationship explicit. C) To guarantee all inputs are valid. D) To make the argument independent of its original object automatically.
Check question 3: answer and explanation
Answer: B. Visible inputs improve reasoning but still need appropriate validation.
Question 4
Which property describes the pure calculation here? A) It updates the DOM. B) It reads current time. C) It mutates a global counter. D) It returns the same result for the same valid inputs without external changes.
Check question 4: answer and explanation
Answer: D. Deterministic output and no external side effects support isolated testing.
Question 5
Why test zero, one, and several seats? A) They exercise distinct result branches. B) They establish correct behavior for every invalid input too. C) They make the stated input contract unnecessary. D) They prove arbitrary large inputs cannot exceed safe numeric limits.
Check question 5: answer and explanation
Answer: A. Deliberate cases cover the logic's meaningful alternatives.