最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Javascript shorthand for calling a callback function if it is not null? - Stack Overflow

programmeradmin8浏览0评论

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
  • 10 For the record, good code is not shorter, it's more readable – Sterling Archer Commented May 8, 2018 at 14:44
  • Agreed, there's nothing wrong with that as it is. – Pointy Commented May 8, 2018 at 14:44
  • This code's syntax is wrong – Phiter Commented May 8, 2018 at 14:44
  • 3 Just if (cb) cb() should do, but if (typeof cb=="function") cb() would be better. Arguably, don't ever use optional callback parameters anyway… – Bergi Commented May 8, 2018 at 14:45
  • 1 cb?.() - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – riv Commented Nov 29, 2020 at 16:36
Add a comment  | 

2 Answers 2

Reset to default 13

Now 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()
发布评论

评论列表(0)

  1. 暂无评论