Files
30-seconds-of-code/js/s/call-or-return.md
Angelos Chalaris 5c913d20bd Reorganize snippets
2023-05-03 21:19:02 +03:00

573 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Call or return snippet javascript
function
chalarangelo cows 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