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.