Skip to content

Latest commit

 

History

History

12 - Default Function Arguments

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Section 12: Default Function Arguments

Specifying or Using Cases of Default Arguments

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);


[Exercise] Using Default Arguments

Question

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;
}

Solution

function sum(a = 0, b = 0) {
  return a + b;
}


[Exercise] Dumping Unused Code

Question

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;
}

Solution

function addOffset(style = {}) {
  style.offset = '10px';

  return style;
}