08_JavaScript : spread & rest

08_JavaScript : spread & rest

Object, Array, ...rest

·

2 min read

(Object) spread

const cake = {
    name: 'cakeeee';
};

const cuteCake = {
    name: 'cakeeee',
    attribute: 'cute'
};

const purpleCuteCake = {
    name: 'cakeeee',
    attribute: 'cute',
    color: 'purple'
};

console.log(cake);
console.log(cuteCake);
console.log(purpleCuteCake);

-> Use 'spread' to make it shorter

const cake = {
    name: 'cakeeee'
};
const cuteCake = {
    ...cake,
    attribute: 'cute'
};
const purpleCuteCake = {
    ...cuteCake,
    color: 'purple'
};

console.log(cake);
console.log(cuteCake);
console.log(purpleCuteCake);

(Array) spread

const animals = ['dog', 'cat', 'bird']
const anotherAnimals = [...animals, 'panda'];
const manyAnimals = [...animals, 'panda', ...animals];
console.log(animals);
console.log(anotherAnimals);
console.log(manyAnimals); // ['dog', 'cat', 'bird', 'panda', 'dog', 'cat', 'bird']

Rest

  • object, array, parameters of the function
// object 
const purpleCuteCake = {
    name: 'cakeeee',
    attribute: 'cute',
    color: 'purple'
};
// 비구조화 할당 문법과 함께 사용(특히 object와 array)
const { color, ...rest } = purpleCuteCake; //rest 이름 바꿔도 됨
console.log(color); //purple
console.log(rest); //{ name: 'cakeeee', attribute: 'cute' }

const { attribute, ...cake01 } = rest;
console.log(attribute); // { name: 'cakeeee', attribute: 'cute'}
console.log(cake01); // { name: 'cakeeee' }
// Array
const numbers = [0, 1, 2, 3, 4, 5, 6];
const [one, ...rest] = numbers; // ...rest는 맨 앞에 못 씀(SyntaxError)
console.log(one); //0
console.log(rest); //[1, 2, 3, 4, 5, 6]
// parameters of the function
function sum(a, b, c, d, e, f, g) {
    let sum = 0;
    if (a) sum += a;
    if (b) sum += b;
    if (c) sum += c;
    if (d) sum += d;
    if (e) sum += e;
    if (f) sum += f;
    if (g) sum += g;
    return sum;
}
const result = sum(1,2,3,4,5,6); // sum function has 7 parameters but I put only 6
// g is undefined so the result is NaN
console.log(result);

-> 함수의 파라미터가 몇개 될지 모르는 상황에서 rest 파라미터 유용

function sum(...rest) {
    return rest;
}
const result = sum(1,2,3,4,5,6);
console.log(result); // [1,2,3,4,5,6]
function sum(...rest) {
    return rest.reduce((acc, current) => acc + current, 0);
}
const result = sum(1,2,3,4,5,6);
console.log(result); // 21

-> 만약 배열 안의 원소들을 모두 파라미터로 넣어주고 싶다면

function sum(...rest) {
    return rest.reduce((acc, current) => acc + current, 0);
}
const numbers = [1,2,3,4,5,6];
const result = sum( //uncomfortable
    numbers[0],
    numbers[1],
    numbers[2],
    numbers[3],
    numbers[4],
    numbers[5]
);
console.log(result);

-> Make it shorter

function sum(...rest) {
    result rest.reduce((acc, current) => acc + current, 0);
}
const numbers = [1,2,3,4,5,6];
const result = sum(...numbers); //배열의 원소 하나하나를 파라미터로 넣어주기 
console.log(result);