LoginSignup
12
11

More than 5 years have passed since last update.

ES6のあの記法について( let { hoge } = obj; )

Last updated at Posted at 2016-01-14

ES6の記法でよく見かける以下の書き方ですが、どういう条件でhogeに値が渡ってくるのかまとめました(名前とかあるのかな分割代入というそうです)

let { hoge } = obj;

今回のサンプルのために以下の関数を用意しました

function out(val) {
  let { value = 'no value' } = val;
  console.log(value);
}

値が渡ってこないパターン

out({});
結果
no value
out({ value: undefined });
結果
no value

値が渡ってくるパターン

out({ value: 'has value' });
結果
has value
out({ value: null });
結果
null

その他の記法

let { value: temp = 'no value' } = val;

これは以下のような挙動になります

  • valにプロパティvalueが有る時 → valueの値がtempに入る
  • valにプロパティvalueが無い時 → 'no value'がtempに入る

今回のサンプルはこちらに

12
11
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11