JavaScript/DreamCoding

JavaScript tip2

느리지만 꾸준하게 2021. 8. 4. 17:07

tip1에 이어서 Spread-syntax-object에 대해서 알아보면 

item과 detail이라는 두가지의 오브젝트를 한번에 묶을 수 있는 방법은 기존에 존재하는 item이라는 오브젝트에 detail의 키와 벨류들을 수동적으로 넣어서 업데이트 할 수가 있다. 기존의 오브젝트를 변경 mutation하는 것은 좋지 않다.

const item = { type: '👖', size: 'M'};
const detail = { price: 20, made: 'Korea', gender: 'M'};


// Bad Code 💩
item['price'] = detail.price;

새로운 오브젝트를 만들어보면 item의 키의 값들 detail의 키와 값들을 수동적으로 하나하나씩 할당해주는 방법이 있을 것이다. 이거또한 Bad Code이다.

 

새로운 오브젝트를 만드는 좀 더간편한 syntax를 이용해서 {}사용하는 거도 있는데 아래거도 수동적으로 할당하고 있으니까 똥코드이다.

// Bad Code 💩
cosnt newObject = new Object();
newObject['type'] = item.type;
newObject['size'] = item.type;
newObject['price'] = item.type;
newObject['made'] = item.type;
newObject['gender'] = item.type;
// Bad Code 💩
cosnt newObject2 = {
    type: item.type,
    size: item.size,
    price: detail.price,
    made: detail.made,
    gender: detail.gender,
};

이렇게 하나하나씩 수동적으로 복사하는 것이 아니라 좀 더 간편하게 하는 방법은 Object.assign함수를 이용해서 함께 묶고 싶은 item과 detail을 전달하면 shirt라는 변수에는 item detail 모든 키와 벨류들이 합해져서 할당된다.

 

spread syntax를 이용하고 싶으면 better code로 이용하면 된다. 새로운 오브젝트를 만들 수 있는 { }를 이용해서 

만든다음에 spread syntax를 이용해서 item에 있는 모든 키와 벨류를 한개씩 가지고 오고 그리고 detail에 있는 key와 value들을 하나하나씩 나열해서 모두 가져올 수 있다.

 

이렇게 spread syntax를 이용했을 때 좋은점은 만약에 detail에 있는 price값을 덮어씌우고 싶으면 뒤에다가 원하는 값으로 업데이트가 된다. 그러면 기존에 price값말고 새로 할당한 값이 반영된다

// Good code💥
const shirt0 = Object.assign(item, detail);

// Better! Code 💥
const shirt = { ...item, ...detail};

const shirt = { ...item, ...detail, price: 40};

spread syntax는 오브젝트뿐만 아니라 array 배열에도 사용되어 질수 있다. 기존에 과일 배열에서 다른 과일을 추가하고싶으면 push와 unshift와 같은 방법처럼 아래와 같이 나타낼 수 있다.

//Spread Syntax - Array
let fruits = ['🍎', '🍑', '🍌']l

// fruits.push('🍓');
fruits = [...fruits, '🍓'];

// fruits.unshift('🍋');
fruits = ['🍋', ...fruits];

기존의 fruits 배열과 다른 fruits2 배열을 묶고 싶으면 concat라는 함수를 이용해서 묶을 수 있고

다른 아이템을 추가하고 싶으면 아래와 같이 중간에 과일을 넣어서 나타내면 된다.

const fruits2 = ['🥥', '🍏', '🍉'];
let combined = fruits.concat(fruits2);
combined = [...fruits, '🍐', ...fruits2];

 

다음으로 Optional Chaining에 대해서 알아보면 

bob은 일자리를 못구했고 anna는 일자리를 구했다라고 하자

일자리를 표현할 수 있는 코드를 작성하면 person의 job이 있고 job의 title이 있다면 표현하는 코드가 있다.

아래 코드는 bad code이다.

// Optional Chaining

const bob = {
    name: 'Julia',
    age: 20,
};

const anna = {
    name: 'Julia',
    age: 20,
    job: {
        title: 'Software Engineer',
    },
};

// 💢 Bad Code 💩
function displayJobTitle(person) {
    if (person.job && person.job.title) {
        console.log(person.job.title);
    }
}

깔끔하게 optional-chaining을 이용하게 되면

job이 있다면 if문이 실행이 되고 job이 없다면 fasly가 되므로 if문이 실행이 안된다.

// Good Code💥
function displayJobTitle(person) {
    if (person.job?.title) {
        console.log(person.job.title);
    }
}

그리고 optional chaining과 앞에서 살펴본 nullish-coalescing을 이용해서 job이 있고 title이 있으면 title을 출력하고 없으면 No job Yet을 출력하도록 하는 Good Code를 나타낼 수 있다.

// Good Code💥
function displayJobTitle(person) {
    const title = person.job?.title ?? 'No Job Yet 💢';
    console.log(title);
}

 

다음으로 template-literals에 대해서 보면

person에 있는 데이터를 다른 문자열과 +를 이용해서 계속적으로 결합하기 보다는

// Template Literals (Template String)
const person = {
    name: 'Julia',
    score: 4,
};

// Bad Code 💩
console.log(
    'Hello ' + person.name + ', your current score is: ' + person.score
);

 ` 백틱키와 ${}을 이용해서 간단하게 아래와 같이 나타낼 수 있다.

// Good Code 💥
console.log(`Hello ${person.name}, Your current score is: ${person.score}`)

object destructing을 이용해서 더 간단하게 아래와 같이 나타낼 수 있다.

// Good Code 💥
const {name, score} = person;
console.log(`Hello ${name}, Your current score is: ${score}`);

재사용이 가능한 greetings라는 함수를 만들어서 확장성 있게 만들 수도 있다.

// Good Code 💥
function greetings(person) {
    const { name, score } = person;
    console.log(`Hello ${name}, Your current score is: ${score}`); 
}

 

 

참고: https://www.youtube.com/watch?v=BUAhpB3FmS4 

 

'JavaScript > DreamCoding' 카테고리의 다른 글

JavaScript tip3  (0) 2021.08.04
JavaScript Tip1  (0) 2021.08.04
class 예제 & 콜백 함수 재정리  (0) 2021.08.03
boolean과 && 연산자  (0) 2021.08.03
함수 정의, 호출, 콜백함수  (0) 2021.08.03