Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript shorthand for calling a callback function if it is not null?

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.

like image 398
Ole Avatar asked Jun 07 '26 12:06

Ole


1 Answers

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 not a non null/undefined value, (eg 23 or false) then this will throw a TypeError.

like image 136
Tom Avatar answered Jun 09 '26 01:06

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!