Destructuring Assignment
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
const arr = [1,2,3];
기존
const one = arr[0];
const two = arr[1];
const three = arr[2];
ES6 Destructuring Assignment
const [one,two,three] = arr;
console.log(one,two,three); //1,2,3
const [first,...rest] = arr;
console.log(first,rest); //1,[2,3]
const [, ,three] = arr;
console.log(three); //3
const arr = [undefined, 'pizza', 'icecream'];
const [kfc = 'chicken', domino, baskin] = arr;
arr[0] === undefined이므로 이 경우 변수 kfc에 기본값으로 'chicken'을 할당해준다.
const obj = {key1: 'number1', key2:'number2', key3:'number3'}
기존
const v1 = obj.key1;
const v2 = obj.key2;
const v3 = obj.key3;
ES6 Destructuring Assignment
const {key1, key2, key3} = obj;
중괄호 안에 할당할 변수명으로 객체의 키를 쓰면 문제가 없지만 객체의 키가 아닌 변수명만 쓰게 되면, 변수는 다음과 같이 undefined를 리턴한다.
따라서 다음과 같은 형식으로 (key이름: 변수이름) 작성해줘야 한다.
const {key1,...rest} = obj;
console.log(key1, rest);
//'number1', {key2: 'number2', key3: 'number3'}
const obj = {
kfc: undefined,
domino: 'pizza',
starbucks: 'coffee'
}
console.log(obj.kfc); //undefined
const {kfc='chicken'} = obj;
console.log(kft); //'chicken'
const user = {
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe'
}
};
function userId({id}) {
return id;
}
function whois({displayName, fullName: {firstName: name}}) {
return `${displayName} is ${name}`;
}
console.log(userId(user));
console.log(whois(user));