I want to add default value for function parameter expect to receive a function.
Look at the following example:
/**
* @param {function} callback
* @param {String} name
*/
function example(callback, name){
console.log('Hello' + name + 'from parent function');
callback();
}
// implementation
example(null, "Mickey");
I want to make the callback
as optional parameter.
Answer
In JavaScript you typically test whether the parameter is null
or undefined
and provide a default. More succinctly you can use ||
:
callback = callback || (some default value);
Using ||
is looser because it will also treat anything that's "falsy" in JavaScript as missing, including false
, an empty string and zero. So it's not useful for optional boolean parameters.
In your case, your default value is a function:
function example(opt_callback, name) {
var callback = opt_callback || function() {};
console.log('Hello' + name + 'from parent function');
callback();
}
Here the default function provides nothing, but you could add some default behavior to the default function here.
Naming optional arguments with opt_
is a practice recommended by the Google JavaScript Style Guide and Google Closure Compiler. I think it makes code more readable, but maybe I have just gotten used to it.
Unless there are other overriding readability reasons, it is good to put optional arguments at the end of the parameter list, for example:
function example(name, opt_callback) {
...
That way callers can succinctly call your function with just one argument, for example example('Mickey')
, because the default value of unspecified arguments in JavaScript is undefined
.
No comments:
Post a Comment