function read_file(file, delete_after) {
delete_after = delete_after || "my default here";
//rest of code
}
This assigns to delete_after
the value of delete_after
if it is not a falsey value otherwise it assigns the string "my default here"
. For more detail, check out Doug Crockford's survey of the language and check out the section on Operators.
This approach does not work if you want to pass in a falsey value i.e. false
, null
, undefined
, 0
or ""
. If you require falsey values to be passed in you would need to use the method in Tom Ritter's answer.
When dealing with a number of parameters to a function, it is often useful to allow the consumer to pass the parameter arguments in an object and then merge these values with an object that contains the default values for the function
function read_file(values) {
values = merge({
delete_after : "my default here"
}, values || {});
// rest of code
}
// simple implementation based on $.extend() from jQuery
function merge() {
var obj, name, copy,
target = arguments[0] || {},
i = 1,
length = arguments.length;
for (; i < length; i++) {
if ((obj = arguments[i]) != null) {
for (name in obj) {
copy = obj[name];
if (target === copy) {
continue;
}
else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
};
to use
// will use the default delete_after value
read_file({ file: "my file" });
// will override default delete_after value
read_file({ file: "my file", delete_after: "my value" });