What is a function?
In computer science, a function is a reusable block of code that:
- takes inputs (often called parameters or arguments),
- performs a computation, and
- produces an output (often called a return value).
Functions help you write code that is easier to test, reuse, and understand.
Inputs → Output
Many functions can be thought of like math: you feed in values and get a result.
// Example (JavaScript)
function add(a, b) {
return a + b;
}
add(2, 3); // 5
Side effects
Some functions also change the outside world (printing, saving files, network calls). Those changes are called side effects.
# Example (Python)
def greet(name):
print("Hello,", name) # side effect: prints to screen
Broken or Fixed: a simple checklist
When you say a function is broken, it typically fails one of these:
Correctness
- Returns the right output for typical inputs
- Handles edge cases (empty, negative, very large)
- Avoids off-by-one errors
Reliability
- Doesn’t crash unexpectedly
- Validates input types/ranges
- Has clear error handling
Performance
- Runs quickly enough for the use case
- Uses memory reasonably
- Scales with input size
Clarity
- Readable name and parameters
- Small and focused responsibility
- Documented assumptions
A function is fixed when it meets the expected behavior consistently and predictably.
Examples: broken vs fixed
Example 1: division
// Broken: doesn't handle divide-by-zero
function divide(a, b) {
return a / b;
}
// Fixed: validates input and gives a clear error
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero.");
return a / b;
}
Example 2: summing an array
# Broken: fails on empty list, and assumes numeric inputs
def sum_list(nums):
total = nums[0]
for n in nums[1:]:
total += n
return total
# Fixed: handles empty list and validates numbers
def sum_list(nums):
total = 0
for n in nums:
if not isinstance(n, (int, float)):
raise TypeError("All elements must be numbers.")
total += n
return total
Key ideas (quick reference)
Parameters vs arguments
Parameters are names in the function definition. Arguments are values you pass in.
Pure functions
A pure function returns the same output for the same input and has no side effects.
Big-O
Big-O describes how runtime/memory grows as inputs get larger (e.g., O(n), O(n log n), O(n²)).
Testing
Unit tests check expected inputs/outputs. Add edge cases to catch “broken” behavior early.
Practice prompts
- Write a function that validates an email address format.
- Write a function that returns the median of a list of numbers (handle even and odd lengths).
- Write a function that parses a date string and rejects invalid dates.
- Improve a function’s performance by changing an O(n²) loop to O(n) using a hash map.