Call or return

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

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • Attempt invoking a function

    Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.

    JavaScript, Function · Oct 18, 2020

  • Rearrange function arguments

    Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.

    JavaScript, Function · Oct 22, 2020

  • Transform function arguments

    Creates a function that invokes the provided function with its arguments transformed.

    JavaScript, Function · Oct 21, 2020