Destructuring Assignment

Creating the dots·2021년 7월 2일
0

Javascript

목록 보기
12/24

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.

Array and destructuring assignment

const arr = [1,2,3];

기존

const one = arr[0];
const two = arr[1];
const three = arr[2];

ES6 Destructuring Assignment

변수 1대 1 매치

const [one,two,three] = arr;
console.log(one,two,three); //1,2,3

...rest

const [first,...rest] = arr;
console.log(first,rest); //1,[2,3]

Ignore values

const [, ,three] = arr;
console.log(three); //3

default value : set a default value in case the value in the array is undefined

const arr = [undefined, 'pizza', 'icecream'];
const [kfc = 'chicken', domino, baskin] = arr;

arr[0] === undefined이므로 이 경우 변수 kfc에 기본값으로 'chicken'을 할당해준다.

Object and destructuring assignment

const obj = {key1: 'number1', key2:'number2', key3:'number3'}

기존

const v1 = obj.key1;
const v2 = obj.key2;
const v3 = obj.key3;

ES6 Destructuring Assignment

변수 1대 1 매치

const {key1, key2, key3} = obj;

중괄호 안에 할당할 변수명으로 객체의 키를 쓰면 문제가 없지만 객체의 키가 아닌 변수명만 쓰게 되면, 변수는 다음과 같이 undefined를 리턴한다.

따라서 다음과 같은 형식으로 (key이름: 변수이름) 작성해줘야 한다.

...rest

const {key1,...rest} = obj;
console.log(key1, rest); 
//'number1', {key2: 'number2', key3: 'number3'}

default value

const obj = {
  kfc: undefined,
  domino: 'pizza',
  starbucks: 'coffee'
}
console.log(obj.kfc); //undefined

const {kfc='chicken'} = obj;

console.log(kft); //'chicken'

Unpacking fields from objects passed as a function parameter

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)); 
profile
어제보다 나은 오늘을 만드는 중

0개의 댓글