0

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.

Lion King
  • 32,851
  • 25
  • 81
  • 143

2 Answers2

1

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.

Dominic Cooney
  • 6,317
  • 1
  • 26
  • 38
-1

Since a function has a typeof "function", you could do a simple typeof check. Though JavaScript functions are first-class, so you don't really need to change much.

/** 
* @param {function} callback
* @param {String} name
*/
function example(callback, name){
    if (typeof a !== "function") {
      callback = function(){ }; // replace this with your default function
    }
    console.log('Hello' + name + 'from parent function');
    callback();
}

For more in-depth answers please consult the protected answer here

EDIT: Just as an aside, it is better practice to make your optional callback the second parameter. that way you don't have to explicitly pass null to get a default value.

function example(name, callback) { ... }

example("hello"); // callback has value null

example("hello", function(){...}); // also valid
Community
  • 1
  • 1
Jonah Williams
  • 20,499
  • 6
  • 65
  • 53
  • A good native no-operation function in _JavaScript_ is [`Function.prototype`](http://es5.github.io/#x15.3.4) – Paul S. Oct 18 '15 at 22:11
  • no, its just a nothing function. replace it with whatever you like, a better do nothing function is just function( ){ } – Jonah Williams Oct 18 '15 at 22:20