Some languages - like Ruby, CoffeeScript and upcoming JavaScript versions - can declare default parameters when defining a function, like this:
// Outputs: "first string" and "second string"
myFunc("first string");
// Outputs: "first string" and "second string version 2"
myFunc("first string", "second string version 2");
Unfortunately, in the current version of javascript, this way of writing is invalid. So, what can we do to achieve this, using our existing toolset?
The simplest solution is like this:
console.log(param1, param2);
}
// Outputs: "first string" and "second string version 2"
myFunc("first string", "second string version 2");
The fact is that an omitted parameter is always "undefined" when accessed. This is a good solution if you only have one parameter, but what if you have more than one?
If you have more than one parameter, you can use an object as the parameter, which has the advantage that each parameter has a clear name. If you pass an object parameter, you can declare a default value in the same way.
var finalParams = defaultParams;
// We iterate over each property of the paramObject
for (var key in paramObject) {
// If the current property wasn't inherited, proceed
If (paramObject.hasOwnProperty(key)) {
// If the current property is defined,
// add it to finalParams
If (paramObject[key] !== undefined) {
finalParams[key] = paramObject[key];
}
}
}
console.log(finalParams.param1,
finalParams.param2,
finalParams.param3);
}
myFunc({param1: "My own string"});
This is a bit clumsy. If you use this method in many places, you can write a wrapper function. Fortunately, many libraries now have related methods, such as the extend method in jQuery and Underscore.
The following uses Underscore’s extend method to achieve the same result as above:
var finalParams = _.extend(defaultParams, paramObject);
console.log(finalParams.param1,
finalParams.param2,
finalParams.param3);
}
// Outputs:
// "My own string" and "second string" and "third string"
myFunc({param1: "My own string"});
This is how you can get default parameters, in current javascript versions.
We welcome criticism and correction of any inaccuracies in the article.