Chapter 08
Functions
As programs grow, you find yourself writing the same few lines again and again. A function lets you write those lines once, give them a name, and then run them whenever you like just by saying the name. It's the single most important tool for keeping code organised.
Think of a function as a little machine: you feed it some inputs, it does its job, and it hands you back a result.
Defining and Calling a Function
You create a function with the word function, a name, brackets, and a block of code. Defining it doesn't run it - it just teaches JavaScript the recipe. You run it later by writing its name followed by brackets, which is called "calling" it:
function sayHello() {
console.log("Hello there!");
}
sayHello(); // Hello there!
sayHello(); // Hello there! - call it as many times as you wantThe brackets are what actually runs it. Writing sayHello without brackets refers to the machine; writing sayHello() presses its button.
Inputs: Parameters
A function is far more useful when you can give it different inputs. Names you put in the brackets when defining it are called parameters - placeholders for values you'll supply later:
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Ada"); // Hello, Ada!
greet("Grace"); // Hello, Grace!When you call greet("Ada"), the value "Ada" is dropped into the name placeholder for that run. You can have several parameters, separated by commas:
function greetFully(firstName, lastName) {
console.log(`Hello, ${firstName} ${lastName}!`);
}
greetFully("Ada", "Lovelace"); // Hello, Ada Lovelace!Outputs: return
Printing is nice, but usually you want a function to compute a value and hand it back so you can use it. The word return does that - it's the function's output:
function add(a, b) {
return a + b;
}
const sum = add(3, 4);
console.log(sum); // 7Here add(3, 4) runs the function and becomes the value 7, which we store in sum. The difference between printing and returning is crucial: console.log shows a value to you, the human; return gives a value back to the program to use.
return also ends the function immediately - any code after it doesn't run. A function with no return hands back undefined.Why Functions Matter
Once something is a function, you can reuse it, test it, and give it a clear name that explains intent. Compare doing a calculation inline versus behind a well-named function:
function priceWithTax(price) {
return price * 1.2; // add 20%
}
console.log(priceWithTax(10)); // 12
console.log(priceWithTax(50)); // 60If the tax rate ever changes, you fix it in one place. And anyone reading priceWithTax(10) instantly understands what it does. Small, well-named functions are the backbone of readable programs.