Functions, Scope & Object Model
Functions as Values
Functions are first-class objects in JavaScript: they can be passed, returned, stored, decorated, bound, and composed. This is the foundation of callbacks, middleware, event handlers, array methods, and functional-style APIs.
- A function value can move independently from its original name
- Higher-order functions take or return functions
- A function can carry a closure
- Call signature and object identity are separate ideas
- Detached methods can lose
this
function withTiming(fn) {
return async (...args) => {
const start = performance.now()
try {
return await fn(...args)
} finally {
console.log(`took ${performance.now() - start}ms`)
}
}
}
const timedFetchUser = withTiming(fetchUser)| Pattern | Shape | Example |
|---|---|---|
| Callback | Pass function to run later | button.addEventListener('click', handler) |
| Mapper/filter | Pass transformation/predicate | items.map(fn), items.filter(fn) |
| Factory | Return configured function | createValidator(schema) |
| Decorator | Wrap another function | withRetry(fetcher) |
| Middleware | Chain functions around request | auth → handler → logger |