Details of the default parameters in Javascript
- 2020-03-30 04:11:28
- OfStack
Some languages -- like Ruby,CoffeeScript, and upcoming javascript versions -- can declare default parameters when defining a function, as follows:
function myFunc(param1, param2 = "second string") {
console.log(param1, param2);
}
// 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 is not valid. So, what can we do to implement this approach, using our existing toolset?
The simplest solution is something like this:
function myFunc(param1, param2) {
if (param2 === undefined) {
param2 = "second string";
}
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. If you only have one parameter, that's a good solution. What if you have multiple parameters?
If you have more than one argument, you can use an object as an argument, which has the advantage of giving each argument a specific name. If you pass an object parameter, you can declare the default value in the same way.
function myFunc(paramObject) {
var defaultParams = {
param1: "first string",
param2: "second string",
param3: "third string"
};
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 unwieldy, and if you use it in a lot of places, you can write a wrapper function. Fortunately, there are a lot of libraries out there with methods like jQuery and extend methods in Underscore.
Now use the Underscore's extend method to achieve the same result as above:
function myFunc(paramObject) {
var defaultParams = {
param1: "first string",
param2: "second string",
param3: "third string"
};
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 get the default parameters in the current version of javascript.
Criticism is welcome if there is anything wrong with the passage.