shou2017.com
JP

Specifying Default Parameters for Functions in JavaScript ES6

Tue Apr 9, 2019
Sat Aug 10, 2024

Until ES5, specifying default parameters for functions was written like this:

function makeAjaxRequest(url, method) {
  if (!method) {
    method = 'GET'
  }
return method;
}

makeAjaxRequest('google.com');
=> GET
makeAjaxRequest('google.com', 'POST');
=> POST

In ES6, you can set the desired default value in the parameter section:

function makeAjaxRequest(url, method = 'GET') {
return method;
}

makeAjaxRequest('google.com');
=> GET
makeAjaxRequest('google.com', 'POST');
=> POST

If you want to set it to null:

function makeAjaxRequest(url, method = 'GET') {
return method;
}

makeAjaxRequest('google.com', null);
=> null
makeAjaxRequest('google.com', 'POST');
=> POST

Note that if you set it to undefined, it will be interpreted as if nothing was specified, and the default value GET will be returned.

See Also