3. Functions & scope
JavaScript · 56 pages source format
Functions are first-class: assign them, pass them, return them. Arrow functions vs function declarations. Scope (block vs function), hoisting intuition, and default parameters. Pure functions — same input, same output, no side effects — are the foundation of testable code.
What you'll learn
- Function declarations vs expressions
- Arrow functions
- Parameters & defaults
- Block scope
- Return early pattern
Three ways to write functions
Declaration: function foo() {} — hoisted. Expression: const foo = function() {} — not hoisted. Arrow: const foo = () => {} — concise, no own this (important later).
function isEven(n) { return n % 2 === 0 }
const isEvenExpr = function(n) { return n % 2 === 0 }
const isEvenArrow = (n) => n % 2 === 0Do this now
Write isEven(n) three ways. Verify all return the same results.
Parameters and defaults
Default parameters replace undefined. Rest params (...args) collect remaining arguments into an array.
function greet(name = "Guest", greeting = "Hello") {
return `${greeting}, ${name}!`
}
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0)
}
sum(1, 2, 3, 4) // 10Do this now
Write greet(name = "Guest", greeting = "Hello") and sum(...numbers) that adds any count of args.
Scope rules
Variables declared with let/const are block-scoped — visible only inside {}. Functions create their own scope. Inner functions can read outer variables (closure preview).
Do this now
Write nested functions where inner reads an outer variable. Try accessing it outside — confirm ReferenceError.
Pro tip. If a variable is only used inside one block, declare it inside that block.
Pure functions and early return
Pure functions: no mutation of external state, no I/O. Return early on invalid input instead of deep nesting.
Do this now
Write titleCase(str) — capitalize first letter of each word. Return "" for empty input. No side effects.
Higher-order functions preview
Functions that take or return functions. Array methods (next chapter) are built on this. Callbacks are everywhere in async code.
Do this now
Write repeat(n, fn) that calls fn n times. Use it to print "tick" three times.