4. Destructuring (JS style guide)

코비코 koreanvisionarycoder ㅣ 2022. 12. 2. 11:09

 

[JS] 구조 분해 할당 (destructing assignment)

구조 분해 할당은 객체나 배열을 변수로 분해할 수 있게 해주는 문법이다. 함수에 객체 또는 배열의 일부만 전달하고자 하는 경우에 사용할 수 있다. 1. 배열 분해 배열을 분해하고 변수에 초기

ingnoh.tistory.com

  • Use object destructuring when accessing and using multiple properties of an object.
    • 단일 오브젝트의 여러 프로퍼티접근하는 경우 Destructing을 사용합니다.
    • 이를 통해 프로퍼티를 위한 임시적인 참조를 줄일 수 있습니다.

 

prefer-destructuring 


  • 임시 references 생성을 줄여 줍니다. 
// bad
function getFullName(user) {
  const firstName = user.firstName;
  const lastName = user.lastName;

  return `${firstName} ${lastName}`;
}

// good
function getFullName(obj) {
  const { firstName, lastName } = obj;
  return `${firstName} ${lastName}`;
}

// best
function getFullName({ firstName, lastName }) {
  return `${firstName} ${lastName}`;
}

 

prefer-destructuring : 배열 destructuring


Use array destructing

  • 배열 또한 destructing을 활용합니다.
const arr = [1, 2, 3, 4];

// bad
const first = arr[0];
const second = arr[1];

// good
const [first, second] = arr;

 

리턴값이 여러개 일 때 : 객체 비구조화 > 배열 비구조화


  • 객체 비구조화는, 추후에 코드에 새 속성을 추가 할 수 있다.
  • 리턴 값을 순서에 상관없이 가져올 수 있다.
  •  호출 할 때, 원하는 data 를 선택할 수 있다.
// bad
function processInput(input) {
  // then a miracle occurs
  return [left, right, top, bottom];
}

// 호출을 할 때 반환값의 순서를 고려해야 하는 문제가 있다.
const [left, __, top] = processInput(input);

// good
function processInput(input) {
  // then a miracle occurs
  return { left, right, top, bottom };
}

// 호출 할 때, 원하는 data 를 선택할 수 있다.
const { left, top } = processInput(input);

'JS > 자바스크립트 Style Guide' 카테고리의 다른 글

6. Functions (JS style guide)  (2) 2022.12.14
5. Strings (JS style guide)  (0) 2022.12.07
3. Arrays (JS style guide)  (0) 2022.11.22
2. Objects (JS style guide)  (0) 2022.11.18
1. References (JS style guide)  (0) 2022.11.18