1. What Is a Function?
A Function is a self-contained block of reusable code designed to perform a specific task. You define the logic once, and you can invoke (call) it hundreds of times with different inputs.
2. Why Do We Use Functions? (The DRY Principle)
1. DRY (Don't Repeat Yourself)
Eliminates copy-pasted code. Fix bugs in one single function definition.
2. Modularity & Abstraction
Hides complex computation behind clean descriptive names like calculateTax().
3. Testability
Small isolated functions are easy to unit-test with automated test runners.
3. Creating and Calling a Function
function greetUser(username) {
console.log(`Welcome back, ${username}!`);
}
// 2. Function Invocation (Calling the function)
greetUser("Alex"); // Logs: "Welcome back, Alex!"
greetUser("Maya"); // Logs: "Welcome back, Maya!"
4. Parameters vs Arguments: The Vital Distinction
Parameters (Placeholders)
The variable names listed in the function header: function add(a, b). Here a and b are parameters.
Arguments (Concrete Values)
The actual data passed into the function when calling it: add(10, 20). Here 10 and 20 are arguments.
5. Return Values and Early Exits
return a * b; // Passes computation result back to caller
}
const result = multiply(5, 4); // result holds 20
console.log(result); // 20
return statement. Any lines written below return in the same block are ignored!6. Function Expressions
const calculateDiscount = function(price, discount) {
return price - (price * discount);
};
console.log(calculateDiscount(100, 0.2)); // 80
7. Modern ES6 Arrow Functions: Clean & Concise
const add = (a, b) => {
return a + b;
};
/* One-Liner with Implicit Return (no braces, no return keyword needed!) */
const double = x => x * 2;
console.log(double(15)); // 30
8. Default Parameters: Preventing Undefined Bugs
return price + (price * taxRate);
}
console.log(applyTax(100)); // 108 (used default 8% tax)
console.log(applyTax(100, 0.15)); // 115 (used custom 15% tax)
9. Local Function Scope & Lexical Closures
Variables declared inside a function body cannot be accessed from the outside world:
const secretCode = "XY-99"; // Local scope
}
// console.log(secretCode); ❌ ReferenceError: secretCode is not defined!
10. Functions as First-Class Citizens
In JavaScript, functions can be assigned to variables, passed as arguments into other functions, and returned from functions just like strings or numbers.
11. Callback Functions — A Gentle Introduction
// Passing an arrow function as a callback to .map()
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
12. Common Function Mistakes
- Forgetting the
returnstatement: Expecting a value from a function that returnsundefined. - Accidental immediate execution in listeners: Writing
button.onclick = doThing()instead ofbutton.onclick = doThing. - Too many arguments: Functions taking more than 3 parameters should accept a single options object instead:
createCard({ title, desc, tag }).
13. 3 Practical Production Functions
1. Currency Formatter
`$${amt.toFixed(2)}`;
2. Email Validator
email.includes('@') &&
email.includes('.');
3. Array Chunker
arr.reduce((a,b)=>a+b,0) /
arr.length;
14. Function Clean Code Best Practices
- Single Responsibility: Each function should do exactly ONE task well.
- Use Verb-Based Names:
getUser(),validatePassword(),renderDashboard(). - Prefer Pure Functions: Avoid mutating external global state.