Facebook Pixel

Real-World Higher-Order Functions in JavaScript

HOFs are used everywhere in real code. Here are practical examples from real applications.

Real-World Higher-Order Functions in JavaScript

Higher-order functions are not just theory. They are used everywhere in real code. Here are practical examples.

1. Event Handlers

function createEventHandler(element, eventType) { return (handler) => { element.addEventListener(eventType, handler); return () => element.removeEventListener(eventType, handler); }; } const onClick = createEventHandler(button, "click"); const cleanup = onClick(() => console.log("clicked")); // later: cleanup(); `` ### 2. Middleware (Express, Redux) ```js function loggingMiddleware(store) { return (next) => (action) => { console.log("dispatching:", action); const result = next(action); console.log("next state:", store.getState()); return result; }; } `` Middleware is a HOF that returns a HOF that returns a HOF. Each layer adds behavior. ### 3. React Higher-Order Components ```js function withAuth(Component) { return function AuthenticatedComponent(props) { if (!props.user) return <Redirect to="/login" />; return <Component {...props} />; }; } const ProtectedPage = withAuth(MyPage); `` A HOC is a HOF that takes a component and returns a new component with added behavior. ### 4. Debounced Search ```js const debouncedSearch = debounce((query) => { fetchResults(query); }, 300); input.addEventListener("input", (e) => debouncedSearch(e.target.value)); `` `debounce` is a HOF that returns a debounced version of the original function. ### 5. Memoized API Calls ```js const fetchUser = memoize(async (userId) => { const res = await fetch(`/api/users/${userId}`); return res.json(); }); fetchUser(1); // network call fetchUser(1); // cached (no network call) `` `memoize` caches results to avoid duplicate API calls. ### 6. Configurable Validators ```js function minLength(n) { return (value) => value.length >= n; } function required(value) { return value !== ""; } const validators = [required, minLength(3)]; const isValid = validators.every((fn) => fn(input)); `` Each validator is a function. `minLength` is a HOF that returns a validator. ### 7. Array Pipelines ```js const pipeline = [ (items) => items.filter((i) => i.active), (items) => items.map((i) => i.name), (names) => names.sort(), ]; const result = pipeline.reduce((acc, fn) => fn(acc), data); `` An array of functions reduced into a pipeline. ### The Takeaway Real-world HOFs: event handlers, middleware (Express, Redux), React HOCs, debounced search, memoized API calls, configurable validators, and array pipelines. HOFs are everywhere in modern JavaScript. Understanding them makes you a better developer.

Event handlers, middleware (Express, Redux), React higher-order components, debounced search, memoized API calls, configurable validators, and array pipelines. HOFs are everywhere in modern JavaScript.

Middleware is a function that takes a store and returns a function that takes next and returns a function that takes action. Each layer is a HOF that adds behavior. Express and Redux middleware work this way.

A function that takes a component and returns a new component with added behavior. It is a higher-order function for components. Example: withAuth(Component) returns a component that redirects to login if not authenticated.

debounce is a HOF that takes a function and a delay, and returns a new function that delays the call until activity stops. The returned function closes over a timer (closure). It is used for search inputs, resize handlers, etc.

Write a HOF that takes a configuration (like a minimum length) and returns a validator function. Example: function minLength(n) { return (value) => value.length >= n; }. Then use validators.every(fn => fn(input)) to check all.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.