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
Higher-order function
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)
The wrapper returns a new function that adds behavior around the original one.
Common function-as-value patterns
PatternShapeExample
CallbackPass function to run laterbutton.addEventListener('click', handler)
Mapper/filterPass transformation/predicateitems.map(fn), items.filter(fn)
FactoryReturn configured functioncreateValidator(schema)
DecoratorWrap another functionwithRetry(fetcher)
MiddlewareChain functions around requestauth → handler → logger
Sources
  • MDN JavaScript Guide and ReferenceFunctions
  • Eloquent JavaScript, 4th EditionHigher-order functions
  • The Modern JavaScript TutorialAdvanced working with functions