Destructuring을 사용하여 자바스크립트에서 필요한 값만 추출하기
객체 디스트럭처링(Object Destructuring)
const person = {
name: 'John',
age: 30,
city: 'New York'
};
// 객체 속성값을 변수로 추출
const { name, age } = person;
console.log(name); // 'John'
console.log(age); // 30
위 예시에서 person
객체의 name
과 age
속성값을 바로 name
과 age
변수로 추출하였습니다. 이렇게 하면 추출된 변수에 해당 속성값이 할당됩니다.
클래스의 인스턴스에서도 동일하게 객체 디스트럭처링을 사용할 수 있습니다.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person('John', 30);
// 클래스 속성값을 변수로 추출
const { name, age } = person;
console.log(name); // 'John'
console.log(age); // 30
배열 디스트럭처링(Array Destructuring)
배열에서도 디스트럭처링을 사용하여 원하는 요소만 추출할 수 있습니다.
const fruits = ['apple', 'banana', 'orange'];
// 배열 요소를 변수로 추출
const [first, second] = fruits;
console.log(first); // 'apple'
console.log(second); // 'banana'
위 예시에서 fruits
배열의 첫 번째와 두 번째 요소를 first
와 second
변수로 추출하였습니다. 변수에는 해당 배열 요소가 할당됩니다.
배열에서 특정 요소를 건너뛰고 추출할 수도 있습니다.
const fruits = ['apple', 'banana', 'orange'];
// 세 번째 배열 요소 추출
const [, , third] = fruits;
console.log(third); // 'orange'
위 예시에서는 fruits
배열의 세 번째 요소인 ‘orange’를 third
변수로 추출하였습니다. 세 번째 변수에는 해당 배열 요소가 할당됩니다.
결론
Destructuring은 자바스크립트에서 필요한 값만 간편하게 추출할 수 있는 기능입니다. 객체 혹은 배열에서 필요한 값을 바로 변수로 할당하기 때문에 코드의 가독성을 높이고, 작성해야 할 코드의 양을 줄일 수 있습니다. 이를 통해 개발 생산성을 향상시킬 수 있습니다.
#JavaScript #Destructuring