Functions Explained: Reusable Logic, Parameters, and Return Values
A function is a self-contained block of reusable code designed to perform a specific task, take optional inputs (parameters), and optionally return a calculated output value.
💡 Plain-English Analogy
Think of a function like a kitchen blender. You pour ingredients in (the parameters or inputs), push a button to execute the blending logic, and pour out the resulting smoothie (the return value). You can use the blender 100 times with different ingredients without having to build a new blender each time.
⚙️ Architecture & Under the Hood
Functions provide modularity, encapsulation, and adhere to the DRY (Don't Repeat Yourself) engineering principle. Modern functional programming favors pure functions—functions with no side effects whose return values depend solely on their input arguments.
Structure of a Pure Function
A well-designed function takes inputs, processes them predictably, and returns an explicit result.
// Pure function: Calculates discounted price without mutating inputs
function calculateDiscount(originalPrice, discountPercent) {
if (originalPrice < 0 || discountPercent < 0 || discountPercent > 100) {
throw new Error("Invalid pricing arguments");
}
const savings = originalPrice * (discountPercent / 100);
return originalPrice - savings;
}
const finalPrice = calculateDiscount(80, 25);
console.log(finalPrice); // 60
Frequently Asked Questions
What is the difference between a function and a method?
A function is an independent block of code. A method is a function that belongs to and is called on a specific object or class (e.g. array.push()).