what does `=` in destructure mean in javascript?

时间:2017-10-12 09:40:20

标签: javascript ecmascript-6

Recently, I read a js file, there's a destructure like below,

IMO, I would write const { files } = obj.props; , but what does const { file=[] } = obj.props mean? why write like this and what's the benefits of this?

const obj = {
  props: {
    files: [1, 2, 3],
  },
};

const { files = [] } = obj.props;
// const { files } = obj.props;
console.log(files);

2 个答案:

答案 0 :(得分:3)

Default values

A variable can be assigned a default, in the case that the value unpacked from the array is undefined.

Source: MDN

const obj = {
  props: { not_files: 1 },
};

const { files = ["default", "value"] } = obj.props;
console.log(files);

答案 1 :(得分:2)

It takes the empty array as default value for the missing property. More under default values or default parameters.

const obj = { props: {} };
const { files = [] } = obj.props;

console.log(files);