TIL no.12 ES6 2

이조은·2020년 7월 12일
0

TIL self-study

목록 보기
12/19
post-thumbnail

아직 안끝 다시 하기

  • destructuring assignment: 오브젝트로부터 바로 추출한 값을 배정하는데 쓰인다.
const user = { name: 'John Doe', age: 34 };
ES5 코드
const name = user.name; // name = 'John Doe'
const age = user.age; // age = 34

ES6 destructuring 구문을 사용한 동일한 지정문
const { name, age } = user;
// name = 'John Doe', age = 34. 여기서 name과 age라는 변수는 만들어지고, user오브젝트로부터 각각의 값을 지정받는다.

새로운 변수 이름을 줄 수도 있다.
const { name: userName, age: userAge } = user;
// userName = 'John Doe', userAge = 34
  • 포함되어 있는 오브젝트에서도 값을 destructure할 수 있다.
const user = {
  johnDoe: { 
    age: 34,
    email: 'johnDoe@freeCodeCamp.com'
  }
};

const { johnDoe: { age, email }} = user;

const { johnDoe: { age: userAge, email: userEmail }} = user;
  • spread operator vs array destructuring
    spread operator unpacks all contents of an array into a comma-separated list. You cannot pick or choose which elements you want to assign to variables
    But, destructurig an array lets us do exactly that
let a = 8, b = 6;
[a, b] = [b, a];

const [a, b] = [1, 2, 3, 4, 5, 6];
console.log(a, b); // 1, 2

destructuring array는 컴마를 사용하여 원하는 인덱스의 값에 접근할 수 있다.
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
console.log(a, b, c); // 1, 2, 5
  • use destructuring assignment with the rest parameter to reassign array elements
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
console.log(a, b); // 1, 2
console.log(arr); // [3, 4, 5, 7]
참고로 원래 어레이의 마지막 요소를 뺀 서브어레이는 the rest parameter를 통해 만들 수 없다.
  • You can destructure the object in a function argument itself
함수로 보내진 오브젝트를 효과적으로 destructure하고 있다.
const profileUpdate = (profileData) => {
  const { name, age, nationality, location } = profileData;
  // do something with these variables
}

더 간단하다. 함수 안에서 전체 오브젝트를 다룰 필요가 없다는 장점이 있다. 필요한 부분은 함수 안에서 복제된다.
const profileUpdate = ({ name, age, nationality, location }) => {
  /* do something with these fields */
}
이해가 잘 안가니 예제를 하나 더 보자
const stats = {
  max: 56.78,
  standard_deviation: 4.34,
  median: 34.54,
  mode: 23.87,
  min: -0.75,
  average: 35.85
};

전체 오브젝트를 패스한다. 그리고 .를 통해서 특정 속성을 고른다.
const half = (stats) => (stats.max + stats.min) / 2.0; 

하지만 stats를 없애보자. max와 min을 얻기 위해 stats를 destructure하고 있다. 두 번째 return문을 stats.max와 stats.min이 아닌 max와 min이라는 것을 잊지 말자.
const half = ({ max, min }) => (max + min) / 2.0;
  • write concise object literal declarations using object property shorhand
const getMousePosition = (x, y) => ({
  x: x,
  y: y
});

ES6에서는 x:x라고 써야하는 중복을 없앤다.
const getMousePosition = (x, y) => ({ x, y });
profile
싱글벙글

0개의 댓글