Call or return

Angelos Chalaris · JavaScript, Function · Apr 4, 2022

Calls the argument if it's a function, otherwise returns it.

  • Use the typeof operator to check if the given argument is a function.
  • If it is, use the spread operator (...) to call it with the rest of the given arguments. Otherwise, return it.
const callOrReturn = (fn, ...args) =>
  typeof fn === 'function' ? fn(...args) : fn;
callOrReturn(x => x + 1, 1); // 2
callOrReturn(1, 1); // 1

Would you like to help us improve 30 seconds of code?Take a quick survey

Recommended snippets