A function is a named, reusable block of logic. Instead of repeating code, you write it once and call it whenever you need it. Functions are the single most important tool for keeping code readable, testable and DRY (Don't Repeat Yourself).
Declaring functions
function greet(name) {return `Hello, ${name}!`;}const message = greet("Aanya"); // call itconsole.log(message); // Hello, Aanya!
A function returns a value with return. If you omit it, the function returns undefined. return also stops the function immediately — handy for early exits.
Arrow functions
Arrow functions are a shorter syntax you'll see everywhere, especially as arguments to other functions. A one-line arrow returns its expression automatically:
const greet = (name) => `Hello, ${name}!`; // implicit returnconst add = (a, b) => a + b;const square = n => n * n; // one param: parens optional// Multi-line needs braces and an explicit returnconst grade = (score) => {if (score >= 75) return "Distinction";return "Pass";};
Parameters & defaults
Give parameters default values, and collect any number of extra arguments with the rest operator ...:
function enrol(name, programme = "Data Analytics") {return `${name} enrolled in ${programme}`;}enrol("Aanya"); // uses the defaultenrol("Rohan", "Full Stack");// Rest: gather all remaining args into an arrayfunction total(...prices) {return prices.reduce((sum, p) => sum + p, 0);}total(100, 250, 90); // 440
Scope
Scope decides where a variable is visible. A variable declared with let/const inside a block { } exists only inside that block. Inner scopes can read outer variables, but not vice-versa:
const outer = "visible everywhere below";function demo() {const inner = "only inside demo";console.log(outer); // ✓ can see outer}demo();// console.log(inner); // ✗ ReferenceError — inner is out of scope
Closures
A closure is a function that "remembers" the variables from where it was created, even after that outer function has finished. It sounds abstract but powers everyday patterns like counters and private state:
function makeCounter() {let count = 0; // private to this counterreturn () => ++count; // the returned fn closes over count}const next = makeCounter();next(); // 1next(); // 2 ← count persists between calls
Practice
Write an arrow function discount(price, pct = 10) that returns the discounted price. Then write a makeGreeter(greeting) that returns a function — a closure — which greets any name with that fixed greeting.
Key takeaways
- 01Functions are reusable logic; return produces a value and exits immediately.
- 02Arrow functions are concise; a one-line arrow returns its expression implicitly.
- 03Parameters can have defaults; the rest operator (...) gathers extra args into an array.
- 04Scope limits where a variable is visible — keep it as narrow as possible.
- 05A closure remembers variables from where it was defined, enabling private, persistent state.
