Back to Code Bytes
2 min read
callAll()

Description

The callAll utility is a higher-order function that creates a new function which executes multiple functions in sequence with the same arguments. It’s particularly useful for combining event handlers or callbacks.

Key features:

  1. Accepts any number of functions as arguments
  2. Returns a new function that can accept any number of arguments
  3. Executes each provided function (if it exists) with the given arguments
  4. Safely handles cases where some functions might be undefined or null

Code Byte

// πŸ’° Here's a little utility that might come in handy
// It accepts any number of functions which returns a function which accepts any number of arguments.
// And for each of the function, it's going to call it if it exists with the arguments.
const callAll = (...fns) => (...args) => fns.forEach(fn => fn && fn(...args));

Use cases:

  • Combining multiple event handlers in React components
  • Implementing middleware-like patterns
  • Extending existing functions without modifying their original implementation

Example usage:

const onClick = callAll(
  () => console.log("Clicked!"),
  props?.onClick,
  analytics?.trackClick
);

// When onClick is called, it will:
// 1. Log "Clicked!"
// 2. Call props.onClick (if it exists)
// 3. Call analytics.trackClick (if it exists)