javascript 関数の引数にオブジェクトリテラルを使用する

javascript 関数の引数にオブジェクトリテラルを使用する

javascriptで、関数の引数にオブジェクトリテラルを使用するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.114

使い方

オブジェクトリテラルを使用すると、関数の引数の順番などを意識せずに引数を指定することが可能です。

以下のオブジェクトリテラルを使用した引数の順番を

function hoge({ name = '', age = 0 }) {
  console.log('名前:' + name);
  console.log('年齢:' + age);
}

hoge({ name: 'mebee', age: 25 });

実行結果

以下のように入れ替えても、同じ結果を得ることが可能です。

function hoge({ age = 0, name = '' }) {
  console.log('名前:' + name);
  console.log('年齢:' + age);
}

hoge({ name: 'mebee', age: 25 });

実行結果

初期値が設定されているので、空のオブジェクトを渡すと初期値が表示されます。

function hoge({ age = 0, name = '' }) {
  console.log('名前:' + name); 
  console.log('年齢:' + age);
}

hoge({})

実行結果