아래와 같이 매개변수 4개를 선언한 함수가 있다. 이 함수는 매개변수를 사용해서 가입환영 템플릿을 생성하고 콘솔에 출력한다.
const getWelcomeTemplate = function (name, age, school, createdAt) {
const myTemplate = `
<html>
<body>
<h1>${name}님 가입을 환영합니다!!!</h1>
<hr>
<div>이름: ${name}</div>
<div>나이: ${age}</div>
<div>학교: ${school}</div>
<div>가입일: ${createdAt}</div>
</body>
</html>
`;
console.log(myTemplate);
}
만약 함수를 호출할 때 모든 매개변수에 아규먼트를 전달하지 않으면 잘못된 가입환영 템플릿이 생성되고 출력된다.
getWelcomeTemplate("철수", 10, "2023-01-10");
// 출력
<html>
<body>
<h1>철수님 가입을 환영합니다!!!</h1>
<hr>
<div>이름: 철수</div>
<div>나이: 10</div>
<div>학교: 2023-01-10</div>
<div>가입일: undefined</div>
</body>
</html>
이런 경우를 방지하기 위해 구조분해할당과 shorthand-property를 사용할 수 있다.
shorthand-property는 객체를 간단하게 표현하는 방법이다.
const name = "캐비지";
const gender = "남성";
const bootcamp = "코드캠프";
const profile = {
name: name,
gender: gender,
bootcamp: bootcamp,
};
// shorthand-property
const profile2 = {
name,
gender,
bootcamp,
};
const qqq = function(aaa) {
console.log(aaa);
};
// 변수에 담아 보내기
qqq(profile);
qqq(profile2);
// 통째로 보내기
qqq({ name, gender, bootcamp });
객체 구조분해할당은 객체의 구조를 분해해서 변수에 할당한다.
const profile = {
name: "캐비지",
gender: "남성",
bootcamp: "코드캠프",
};
// const name = profile.name;
// const gender = profile.gender;
// const bootcamp = profile.bootcamp;
// 객체 구조분해할당 사용
const { name, gender, bootcamp } = profile;
console.log(name, gender, bootcamp);
// 캐비지 남성 코드캠프
객체 구조분해할당을 사용할 때 객체의 키와 일치하지 않는 변수명을 사용하면 값이 제대로 할당되지 않는다.
const getWelcomeTemplate = function (name, age, school, createdAt) {
const myTemplate = `
<html>
<body>
<h1>${name}님 가입을 환영합니다!!!</h1>
<hr>
<div>이름: ${name}</div>
<div>나이: ${age}</div>
<div>학교: ${school}</div>
<div>가입일: ${createdAt}</div>
</body>
</html>
`;
console.log(myTemplate);
}
getWelcomeTemplate("철수", 10, "2023-01-10");
이 함수에 객체 구조분해할당과 shorthand-property를 적용하면 아래와 같다.
function getWelcomeTemplate({ name, age, school, createdAt }) { // 구조분해할당
// const { name, age, school, createdAt } = { name, age, school, createdAt };
const myTemplate = `
<html>
<body>
<h1>${name}님 가입을 환영합니다!!!</h1>
<hr>
<div>이름: ${name}</div>
<div>나이: ${age}</div>
<div>학교: ${school}</div>
<div>가입일: ${createdAt}</div>
</body>
</html>
`;
console.log(myTemplate);
}
const name = "철수";
const age = 10;
const school = "공룡초등학교";
const createdAt = "2023-01-10";
getWelcomeTemplate({ name, age, school, createdAt }); // shorthand-property
// 출력
<html>
<body>
<h1>철수님 가입을 환영합니다!!!</h1>
<hr>
<div>이름: 철수</div>
<div>나이: 10</div>
<div>학교: 공룡초등학교</div>
<div>가입일: 2023-01-10</div>
</body>
</html>
const { name, age, school, createdAt } = { name, age, school, createdAt };의 형태와 같다.함수를 호출할 때 실수로 데이터를 빼먹고 전달하더라도, 객체 구조분해할당을 사용했기 때문에 아규먼트로 사용하는 객체의 키와 동일한 이름의 매개변수에만 값이 undefined로 할당된다.
getWelcomeTemplate({ name, school, createdAt });
// 출력
<html>
<body>
<h1>철수님 가입을 환영합니다!!!</h1>
<hr>
<div>이름: 철수</div>
<div>나이: undefined</div>
<div>학교: 공룡초등학교</div>
<div>가입일: 2023-01-10</div>
</body>
</html>
이와 같이 매개변수에 객체 구조분해할당을 사용하고, 함수를 호출할 때 shorthand-property를 사용하면 그렇지 않을 때보다 안전한 코드를 만들 수 있다.