- Specifying or Using Cases of Default Arguments
- [Exercise] Using Default Arguments
- [Exercise] Dumping Unused Code
The default arguments is the syntax sugar for us to initialize functions with default values and the default values will be used when the arguments is either omitted or undefined
in a function call.
function makeAjaxRequest(url, method = 'GET') {
// logic to make the request
...
}
makeAjaxRequest('https://www.google.com/');
makeAjaxRequest('https://www.google.com/', 'POST');
There is a more complex usage of default arguments.
function User(id) {
this.id = id;
}
function generateId() {
return Math.random * 9999999;
}
function createAdminUser(user = new User(generateId())) {
user.admin = true;
return user;
}
// create a new user when call function
createAdminUser();
// use the given user instead of creating new one
const user = new User(generateId());
createAdminUser(user);
Refactor the following code to use default function arguments. Be sure to remove any unused code after you refactor it.
function sum(a, b) {
if (a === undefined) { a = 0; }
if (b === undefined) { b = 0; }
return a + b;
}
function sum(a = 0, b = 0) {
return a + b;
}
Refactor the following code to use default function arguments. Be sure to remove any unused code after you refactor it.
function addOffset(style) {
if (!style) { style = {}; }
style.offset = '10px';
return style;
}
function addOffset(style = {}) {
style.offset = '10px';
return style;
}