2023-02-09(구조분해할당이란?)

박준혁·2023년 2월 9일
0

✅구조 분해 할당(destructuring assignment)은 JavaScript에서 객체와 배열의 속성이나 요소를 변수로 추출하는 것을 말합니다.

const person = {
  name: 'John',
  age: 30,
  address: {
    city: 'Seoul',
    country: 'Korea'
  }
};

✅이것을 구조분해할당을 사용하면 객체의 속성을 변수로 추출할 수 있다

const { name, age, address } = person;
const { city, country } = address;

console.log(name); // 'John'
console.log(age); // 30
console.log(city); // 'Seoul'
console.log(country); // 'Korea'

✅또한 배열도 구조분해할당이 가능하다

const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor, thirdColor] = colors;

console.log(firstColor); // 'red'
console.log(secondColor); // 'green'
console.log(thirdColor); // 'blue'

✅구조 분해 할당은 함수의 매개변수로도 사용이 가능하다

onst printPerson = ({ name, age }) => {
  console.log(`My name is ${name} and I am ${age} years old.`);
};

printPerson(person);
// My name is John and I am 30 years old.

✅구조분해할당 : 변수 추출 + 함수의 매개변수로도 사용 가능

profile
"열정"

0개의 댓글