If we have:
(cb)=>{ if (cb!=null) cb()}
Is there are shorter way to check if cb is not null and call it? This will be running on Node.
If we have:
(cb)=>{ if (cb!=null) cb()}
Is there are shorter way to check if cb is not null and call it? This will be running on Node.
Share Improve this question edited May 8, 2018 at 17:02 Ole asked May 8, 2018 at 14:42 OleOle 47k68 gold badges237 silver badges441 bronze badges 5 |2 Answers
Reset to default 13Now in 2021 : Optional chaining
cb?.()
If cb is null
- cb is not invoked.
if cb is a func, cb is invoked.
Note: if cb is a not function or a non null/undefined value, (eg 23 or false) then this will throw a TypeError.
You could check cb
directly.
In the case where cb
is a function, you get a truthy value as first check and then it calls the function.
If cb
is null
, then the first part is falsy and the second does not get executed.
cb => cb && cb()
if (cb) cb()
should do, butif (typeof cb=="function") cb()
would be better. Arguably, don't ever use optional callback parameters anyway… – Bergi Commented May 8, 2018 at 14:45cb?.()
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – riv Commented Nov 29, 2020 at 16:36