Why This Matters
As programs grow, you can't write everything as one long list of instructions. You need a way to name a piece of logic, reuse it in multiple places, and compose small pieces into larger systems. That's what functions do.
Functions are the fundamental unit of code organization. Every program you'll ever read — from a 10-line script to a million-line codebase — is built from functions. Master them and you master the building blocks of software.
Define Terms
Visual Model
The full process at a glance. Click Start tour to walk through each step.
A function takes inputs (parameters), does work, and produces an output (return value).
Code Example
// Defining a function
function greet(name) {
return "Hello, " + name + "!";
}
// Calling a function
console.log(greet("Alice")); // "Hello, Alice!"
console.log(greet("Bob")); // "Hello, Bob!"
// Functions with multiple parameters
function add(a, b) {
return a + b;
}
console.log(add(3, 5)); // 8
// Functions with control flow
function letterGrade(score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
return "F";
}
console.log(letterGrade(85)); // "B"
// Arrow function syntax
const double = (x) => x * 2;
console.log(double(7)); // 14
// Functions calling other functions (composition)
function formatScore(name, score) {
return name + ": " + letterGrade(score);
}
console.log(formatScore("Alice", 92)); // "Alice: A"Interactive Experiment
Try these exercises:
- Write a function
isEven(n)that returnstrueifnis even,falseotherwise. - Write a function that calls
isEveninside a loop to print all even numbers from 1 to 20. - What happens if you call a function before you define it? (Try it in both JS and Python.)
- Create a function that calls itself — what happens? (Hint: you need a stopping condition!)
Quick Quiz
Coding Challenge
Write a function called `sumArray` that takes an array of numbers and returns their sum. Then write a function called `average` that uses `sumArray` to compute the average of an array.
Real-World Usage
Functions are the fundamental organizational unit in all software:
- React components are functions that return UI:
function Button({ label }) { return <button>{label}</button> } - API endpoints are functions that handle requests:
app.get('/users', (req, res) => { ... }) - Event handlers are functions triggered by user actions:
onClick,onSubmit,onChange - Utility libraries are collections of functions:
lodash.map(),Math.round(),JSON.parse() - Testing verifies that functions produce correct outputs for given inputs.