Files
30-seconds-of-code/snippets/callOrReturn.md
2022-12-04 22:20:49 +02:00

549 B

title, tags, author, cover, firstSeen
title tags author cover firstSeen
Call or return function chalarangelo blog_images/cows.jpg 2022-04-04T05:00:00-04:00

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