Recipes make a good comparison. A pancake recipe lists its ingredients and steps once; whenever you want pancakes, you follow it again, perhaps with different quantities. Functions give code that same quality. You wrap a set of instructions under a name, and any part of the program can run those instructions by calling that name.
The values you hand over when calling are called arguments, and the names that receive them inside are the parameters. A function can also send a result back to whoever called it by using return.
Example
function applyDiscount(price, percent) {
const saving = price * (percent / 100);
return price - saving;
}
console.log(applyDiscount(80, 25)); // 60
console.log(applyDiscount(15, 10)); // 13.5
The discount logic lives in exactly one place. If the formula ever needs to change, you edit this one definition instead of hunting through every line that works out a discount.
Why split code into functions
Breaking a program into small pieces keeps each one short enough to understand and test by itself. A good function usually does a single job and carries a name that says what that job is, like formatDate or isValidEmail. Variables created inside a function are normally local to it, so they cannot clash with identical names elsewhere.
Function vs method
People often use the two words loosely, but there is a distinction. A plain function stands alone. A method is attached to a class or object, and it runs with access to that object's data. In "hello".toUpperCase(), toUpperCase is a method belonging to the string. In Java, nearly every function is technically a method, because code has to live inside a class.
Where to practise
- Write and call your own functions in the JavaScript editor.
- The JavaScript course covers parameters, return values and arrow functions.
Last updated