개인노트 nomad ES6의 정석 #5 Destructuring

2023. 2. 6. 18:45개인노트-인강

# 5 개요

 

object, array, function의 destructuring 에 대해서 배워보겠습니다.

 

구조 분해 할당
구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 JavaScript 표현식입니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

 

# 5.0 Object Destructuring

 

## Destructuring 을 사용하지 않고 접근하기.

 

const setttings = {
	ontifications: {
    	follow: true,
        alert: true,
        unfollow: false,
    },
    color: {
    	theme: "dark",
    }
};

if(settings.notifications.follow) {
	// send email.
}

 이 경우에 보기에도 안좋고, 찾으려는 follow나 notifications가 없을 경우에는 에러가 발생합니다.

 

## Destructuring 을 사용하여 접근.

 

const setttings = {
	ontifications: {
    	// follow: true,
        alert: true,
        unfollow: false,
    },
    color: {
    	theme: "dark",
    }
};

const { 
	notifications: { follow = false }, // 변수가 존재하지 않을 땐 , default value 출력
	color
} = settings;

console.log(follow); //  출력 : false

 

다른 예

const { 
	notifications: { follow = false } = {},
} = settings;

console.log(follow); //  follow 객체가 없다면, 출력 : false
console.log(notifications); // notifications 객체가 없다면, 출력 : {}

follow 객체가 없을 때는 false를 할당하고, 상위 객체인notifications 객체자체가 없을 때는 빈 객체{} 를 할당합니다.

이렇게 undefined 대신에 설정한 default value를 할당할 수 있습니다.

 

# 5.1 Array Destructuring

 

배열 구조 분해

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

 

개인적으로는 잘 사용하지 않습니다.

Array Destructuring은 가져온 정보를 조작하지 않을 때 쓰기 좋습니다.

예를 들어 API로 부터 응답받은 데이터를 array 형태로 만들어야 하는 상황.

조작하고 싶다면 obejct로 만들어서 object desturcturing 하는 것이 유리할 수도 있습니다.

 

const arr = [10,20,30,40,50];
[a,b,...rest] = arr;
console.log(rest) // [30,40,50]

var foo = ["one", "two", "three"];
const [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"

const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const [mon, tue, wed, name="Jungwoo"] = days;
console.log(mon, tue, wed, name); // Mon Tue Wed Jungwoo

// days가 function이라면?
const days = () => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const [mon, tue, wed, name="Jungwoo"] = days();

 

# 5.2 Renaming

 

// settings 데이터를 api로 부터 받았다고 가정.
const settings = {
	color: {
		chosen_color: "darK",
	},
};

// 방법1 Renaming
const {
	color: { chosen_color: chosenColor = "light" },
} = settings

// ---------------------------------------------------------------

// 방법2 Destructuring 을 ()에 감싸서 이미 존재하는 let 변수를 업데이트 할 수 있습니다.
let chosenColor = "blue";
console.log(chosenColor); // blue

({
	color: { chosen_color: chosenColor = "light" },
} = settings);

console.log(chosenColor); // dark

1. 변수 뒤에 ': 변경할이름' 으로 변수명을 바꿔줄 수 있습니다.
2. Destructuring 을 ()에 감싸서 이미 존재하는 let 변수를 업데이트 할 수 있습니다.

 

# 5.3 Function Destructuring

 

function saveSettings(settings) {
	console.log(settings);
}

saveSettings({
    follow: true,
    alert: true,
    mkt: true,
    color: "green",
});

// 각각의 argument에 값만 보내서 무엇에 대한 값인지를 알 수 없는 것보다,
// 위 처럼하면 객체로 보내면 가독성이 더 좋습니다. 
// 하지만 함수를 호출할 때는 좋지만, 함수를 작성할 때는 안좋습니다.

 

Function Destructuring 를 사용하여

1. 변수들의 가독성을 확보.
2. 각 변수의 기본값을 설정하기.

를 할 수 있습니다.

 

function saveSettings({follow, alert, color = "blue"}) {
	console.log(color);
}

saveSettings({
    follow: true,
    alert: true,
    mkt: true,
    color: "green",
});

 

# 5.4 Value Shorthands

 

변수명 단축

변수 이름이 같다면 단축속성명을 사용할 수 있습니다.

 

const follow = checkFollow();
const alert = checkAlert();

// 단축하기전..
const settings = {
	notifications: {
    	follow: follow,
        alert: alert,
    }
}

// 단축하여..
const settings = {
	notifications: {
    	follow,
        alert,
    }
}

 

# 5.5 Swapping and Skipping

 

자주 쓰는 몇가지 트릭

 

## variable swapping

 

서로 다른 변수의 값을 교환합니다.

let mon = "Sat";
let sat = "Mon";

[sat, mon] = [mon, sat];

console.log(mon, sat);
// 출력
// Mon, Sat

 

## Skipping

 

array에서 필요한 index만 변수로 할당할 수 있습니다.

const days = ["mon", "tue", "wed", "thu", "fri"];
const [, , , thu, fri] = days;

console.log(thu, fri);