Functions: Reusable Code
Wrap work in a name, feed it inputs, get an output back β the single most important structure in programming.
You have already used functions: console.log and
name.toUpperCase() are functions someone else wrote. Now you write your own.
Declaring a function
function greet(name) {
return "Hello, " + name + "!";
}
greet("Ada"); // "Hello, Ada!"
greet("Grace"); // "Hello, Grace!" β same work, different input
Anatomy:
functionβ the keyword that starts a declarationgreetβ the name (verb-like: functions do things)(name)β parameters: named inputs the function expectsreturnβ hands a value back to whoever called the function
Parameters vs arguments
Parameters are the names in the definition; arguments are the actual values passed in a call:
function add(a, b) {
// a, b are parameters
return a + b;
}
add(2, 3); // 2 and 3 are arguments β 5
return ends the function
The moment return runs, the function is done β code below it is skipped.
A function with no return gives back undefined:
function logTwice(msg) {
console.log(msg);
console.log(msg);
} // returns undefined β does work, hands nothing back
function double(n) {
return n * 2;
} // hands 4 back when called with 2
Both styles are legitimate: do something (log, save, update the page) versus compute something (return it). Graders in this course usually call your function, so returning is how you hand results over.
Why functions matter
Functions let you write logic once and trust it everywhere. Fix a bug inside
greet and every call site is fixed. They are also how bigger programs stay
readable: a well-named function is a one-line summary of what it does.
What you learned
- Declare with
function name(parameters) { ... } returnhands a value back and ends the function- No return β
undefined - Write logic once, call it many times
Next: a shorter syntax for functions, and how variable visibility works.