Light Blue Pointer
본문 바로가기
Developing/TIL(Develop)

[React] Destructuring assignment

by Craft Fiend 2024. 9. 27.

어느날 갑자기 리액트를 하게 된 백엔드 개발자의 고군분투기...

회사 : 풀스택 해

 

Java Kotlin 이제 다 필요없어... Destructuring assignment 정말 충격적으로 편리하다

ES6 만세 감사합니다

 

그날도 힘겹게 리액트를 해내고 있던 백엔드 개발자 1은 신기한 코드를 마주하게 된다

const Developer = ({ coffee, sweat, blood }: { coffee: string, sweat: number, blood: string }) => {
  console.log(coffee, sweat, blood);
};
interface Ingredient {
  coffee: string;
  sweat: string;
  blood: string;
}

const Developer = (ingredient: Ingredient) => {
  const { coffee, sweat, blood } = ingredient;
  console.log(coffee, sweat, blood);
};

그리고 그게 Destructuring assignment 이라는 것을 알게 되었다

Array Destructuring

const numbers = [1, 2, 3, 4];

// Old way
const first = numbers[0];
const second = numbers[1];

// Destructuring assignment
const [first, second] = numbers;

console.log(first); // 1
console.log(second); // 2

Object Destructuring

You can also use destructuring to assign object properties to new variables.

const person = {
  name: 'John Doe',
  age: 30,
  job: 'Engineer'
};

// Old way
const name = person.name;
const age = person.age;

// Destructuring assignment
const { name, age, job } = person;

console.log(name); // John Doe
console.log(age); // 30
console.log(job); // Engineer

Default Values

const numbers = [1];

// If there's no second element, use the default value (10)
const [first, second = 10] = numbers;

console.log(first); // 1
console.log(second); // 10

Destructuring in Function Parameters

const person = {
  name: 'Jane Doe',
  age: 25,
  job: 'Designer'
};

function displayPerson({ name, age, job }) {
  console.log(`Name: ${name}, Age: ${age}, Job: ${job}`);
}

displayPerson(person);
// Output: Name: Jane Doe, Age: 25, Job: Designer

Java처럼 매번 ingredient.coffee 이렇게 쓸 필요가 없고 훨씬 편하고 깔끔해지고 직관적인 방법인 것 같다

매일매일 애용하고 있다