shou.com
JP / EN

JS、es6で関数のデフォルト因数を指定する

Tue Apr 9, 2019
Tue Apr 9, 2019

es5までは関数にデフォルト因数を指定する場合、以下のように書いてました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function makeAjaxRequest(url, method) {
  if (!method) {
    method = 'GET'
  }
return method;
}

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

これがes6では、引数のところに与えたいデフォルト値を設定します。

1
2
3
4
5
6
7
8
function makeAjaxRequest(url, method = 'GET') {
return method;
}

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

nullにしたい場合は、

1
2
3
4
5
6
7
8
function makeAjaxRequest(url, method = 'GET') {
return method;
}

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

注意点としてundefinedにすると指定しなかったと解され、デフォルト値のGETが返る。

See Also