Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript style for optional callbacks

I have some functions which occasionally (not always) will receive a callback and run it. Is checking if the callback is defined/function a good style or is there a better way?

Example:

function save (callback){    .....do stuff......    if(typeof callback !== 'undefined'){      callback();    }; }; 
like image 623
henry.oswald Avatar asked Jul 22 '11 15:07

henry.oswald


1 Answers

I personally prefer

typeof callback === 'function' && callback();

The typeof command is dodgy however and should only be used for "undefined" and "function"

The problems with the typeof !== undefined is that the user might pass in a value that is defined and not a function

like image 88
Raynos Avatar answered Sep 19 '22 10:09

Raynos