Concept Explanation
A function is a saved recipe. You write the steps once, give it a name, and then run it whenever you want — with different ingredients each time. This is the golden rule of programming: DRY ("Don't Repeat Yourself").
A function takes inputs (called parameters), does some work, and hands back an output (using return). Picture a coffee machine: you add water and beans (inputs), press a button (call the function), and get coffee (the returned value).
Syntax or Core Structure
Three Ways to Write a Function
// 1. Declaration - "hoisted", usable before it appears in the file
function add(a, b) {
return a + b;
}
// 2. Expression - stored in a variable
const multiply = function (a, b) {
return a * b;
};
// 3. Arrow function - short and modern (deep dive in the ES6 module)
const square = n => n * n;
console.log(add(2, 3)); // 5
console.log(square(4)); // 16
Parameters, Defaults, and Return
function greet(name = "Guest") { // default value when none is passed
return `Welcome, ${name}!`;
}
greet(); // "Welcome, Guest!"
greet("Alice"); // "Welcome, Alice!"
return immediately stops the function and sends a value back. Any code written after return never runs.
Real World Example
Every button on a website runs a function when clicked. A shopping cart calls calculateTotal(items) to add up prices, apply a discount, and return the final number — the same logic reused on each product page, in the cart, and at checkout.
Common Mistakes
- Forgetting
return: A function with noreturngives backundefined.const x = logMessage();leavesxempty if the function only prints. - Calling vs. referencing:
greetis the recipe itself;greet()runs it. Event handlers want the reference:button.onclick = greet, notgreet(). - Too many parameters: More than three arguments gets confusing. Pass a single
optionsobject instead:createUser({ name, age, role }).
Best Practices
- One job per function: A function should do a single thing. If its name needs an "and", split it in two.
- Name with verbs:
getUser,sendEmail,isValid— the name should say what it does. - Prefer pure functions: Same input, same output, and nothing outside is changed. They are the easiest code to test and debug.
- Use default parameters: They erase piles of
if (!x) x = ...checks at the top of a function.
Practice Exercises
- The Converter: Write
celsiusToF(c)that returns the Fahrenheit temperature. Test it with 0, 100, and 37. - The Guard: Write
isAdult(age)that returnstrueorfalse, givingagea default of 0. - The Reducer: Write
sumAll(numbers)that takes an array and returns the total using a loop.