# Today I Learned - Destructuring, Spread Operator(...), Rest Pattern

Hyodduru ·2021년 12월 7일
0

## JavaScript

목록 보기
32/60

강의 출처 : The Complete JavaScript Course 2022 Jonas (Udemy)

Section 9 - Data Structures, Modern Operators and Strings

# 1. Destructuring Arrays

## Destructuring (unpacking) Arrays

const arr = [2, 3, 4];

const [x, y, z] = arr;
console.log(x, y, z);

console.log(arr); // [2,3,4]
const restaurant = {
name: 'Classico Italiano',
location: 'Via Angelo Tavanti 23, Firenze, Italy',
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
};

let [main, secondary] = restaurant.categories;
console.log(main, secondary); // Italian Pizzeria
const [one, , three] = restaurant.categories;
console.log(one, three); // Italian Vegetarian

## Switching variables using destructuring

[main, secondary] = [secondary, main];
console.log(main, secondary); // Pizzeria Italian

## Receive 2 return values from function using destructuring

const restaurant = {
order: function (starterIndex, mainIndex) {
}, }

const [starter, mainCourse] = restaurant.order(2, 0);
console.log(starter, mainCourse); //Garlic Bread Pizza

## Nested destructuring

const nested = [2, 4, [5, 6]];
const [i, , j] = nested;
console.log(i, j); //2 (2) [5, 6]

const [i, , [j, k]] = nested;
console.log(i, j, k); //2 5 6

## Set Default values

const [p = 1, q = 1, r = 1] = [8, 9];
console.log(p, q, r); //8 9 1

# 2. Destructing Objects

참고용 객체

const restaurant = {
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
orderDelivery: function ({
starterIndex = 1,
mainIndex = 0,
time = '20:00',
}) {
console.log(
Order received! ${this.starterMenu[starterIndex]} and${this.mainMenu[mainIndex]}
will be delivered to ${address} at${time}
);
},

openingHours: {
thu: {
open: 12,
close: 22,
},
fri: {
open: 11,
close: 23,
},
sat: {
open: 0, // Open 24 hours
close: 24,
},
},

orderPasta: function (ing1, ing2, ing3) {
console.log(
Here is your delicious past with ${ing1},${ing2} and ${ing3} ); }, orderPizza: function (mainIngredient, ...otherIngredient) { console.log(mainIngredient); console.log(otherIngredient); },} ## Destructing Objects restaurant.orderDelivery({ time: '22:33', address: 'Via del Sole, 21', mainIndex: 2, starterIndex: 2, }); //Order received! Garlic Bread and Risotto //will be delivered to Via del Sole, 21 at 22:33 restaurant.orderDelivery({ address: 'Via del Sole, 21', starterIndex: 1 }); //Order received! Bruschetta and Pizza will be delivered to Via del Sole, 21 at 20:00   const { name, openingHours, categories } = restaurant; console.log(name, openingHours, categories); const { name: restaurantName, openingHours: hours, categories: tags, } = restaurant; console.log(restaurantName, hours, tags); const { menu = [], starterMenu: starters = [] } = restaurant; console.log(menu, starters); //[] (4) ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'] ## Mutating variables let a = 111; let b = 999; const obj = { a: 23, b: 7, c: 14 }; ({ a, b } = obj); // override하기 위해서는 ()로 wrap 해주기! console.log(a, b); // 23 7 ## nested objects const { fri } = openingHours; console.log(fri); // {open: 11, close: 23} const { fri: { open, close }, } = openingHours; console.log(open, close); // 11 23 # 3. The Spread Operator (...) Spread 연산자는 연산자의 대상 배열 또는 이터러블(iterable)을 "개별" 요소로 분리한다. 참고) Iterables : arrays, strings, maps, sets, NOT objects ## ...Arr const arr = [7, 8, 9]; const newArr = [1, 2, ...arr]; console.log(newArr); // [1, 2, 7, 8, 9] 배열의 아이템 하나하나 가져올 수 있다! console.log(...newArr); //1 2 7 8 9 => ... 는 배열 통째로가 아니라 아이템 하나하나가 따로 분리되어 나온다는 특징이 있음 const newMenu = [...restaurant.mainMenu, 'Gnocci']; console.log(newMenu); // building a new array 기존의 배열에 영향 끼치지 않음! ['Pizza', 'Pasta', 'Risotto', 'Gnocci']; ## Copy array const mainMenuCopy = [...restaurant.mainMenu]; ## Join 2 arrays const menus = [...restaurant.starterMenu, ...restaurant.mainMenu]; console.log(menus); //['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad', 'Pizza', 'Pasta', 'Risotto'] const str = 'Jonas'; const letters = [...str, '', 'S.']; console.log(letters); // ['J', 'o', 'n', 'a', 's', '', 'S.'] console.log(...str); //J o n a s //console.log(${...str}); // => error. multiple values separated by a comma 가 올 수 있는 곳 아님!
//It's usually expected when we pass arguments into a function, or when we build a new array

const ingredients = [
prompt("Let's make pasta! Ingredient 1?"),
prompt('Ingredient 2?'),
prompt('Ingredient 3'),
];

restaurant.orderPasta(...ingredients); //(각각의 promt창에 mushrooms, cheese, tomato 입력) Here is your delicious past with mushrooms, cheese and tomato

## ...Objects


const newRestaurant = { foundeIn: 1888, ...restaurant, founder: 'Guiseppe' };
console.log(newRestaurant); //{foundeIn: 1888, name: 'Classico Italiano', location: 'Via Angelo Tavanti 23, Firenze, Italy', categories: Array(4), starterMenu: Array(4), …}

const restaurantCopy = { ...restaurant };
restaurantCopy.name = 'Ristorante Roma';
console.log(restaurantCopy.name); //Ristorante Roma
console.log(restaurant.name); //Classico Italiano

# 4. Rest Pattern and Parameters

Rest는 the spread operator와 같은 형태를 가지고 있으나 정반대의 역할을 한다. rest elements를 배열의 형태로 한꺼번에 묶는다.

## 1) Destructuring

### Arrays

// SPREAD, because on RIGHT side of =
const arr = [1, 2, ...[3, 4]];
console.log(arr); // [1, 2, 3, 4]

// REST, because on LEFT side of =
const [a, b, ...others] = [1, 2, 3, 4, 5]; // ...은 rest라고 불림.
console.log(a, b, others); //1 2 (3) [3, 4, 5]

const [pizza, , risitto, ...otherFood] = [
];
console.log(pizza, risitto, otherFood); //Pizza Risotto (4) ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad']

### Objects

const { sat, ...weekdays } = restaurant.openingHours;
console.log(weekdays); //fri: {open: 11, close: 23} thu: {open: 12, close: 22}

## 2) Functions

Rest 파라미터를 사용하면 함수의 파라미터로 오는 값들을 "배열"로 전달받을 수 있다.

const add = function (...numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum);
};
add(8, 2, 3, 4, 1, 1, 1, 1); //21

const x = [23, 5, 7];

restaurant.orderPizza('mushrooms', 'onion', 'olives', 'spinish');
// mushrooms
// (3) ['onion', 'olives', 'spinish']
restaurant.orderPizza('mushrooms');
// mushrooms
// []


the spread operators is used where we would otherwise write values, separated by comma. On the other hand the rest pattern is basically used where we would otherwise write variable names separated by comma.
The rest pattern can be used where we would write variable names, separated by commas and not values separated by commas

요약
=> spread operator은 value값이 들어가는 자리에 사용된다.

ex)

const arr = [1, 2, ...[3, 4]];

=> rest pattern은 변수이름이 들어가는 자리에 사용된다.
ex)

const [a, b, ...others] = [1, 2, 3, 4, 5];
꾸준히 성장하기🦋 https://hyodduru.tistory.com/ 로 블로그 옮겼습니다