첫번째로 Ternary Operator 삼항연산자에 대해서 알아보면
아래와 같이 💩같은 Bad Code가 있다. score라는 인자를 받아서 score가 숫자 5보다 크다면 엄지척 5보다 작다면 엄지아래를 작성하는 함수이다. 하는 일은 간단한데 코드는 길어보인다.
프로답게 변경해볼려면 점수가 5보다 크다면 엄지척을 아니면은 엄지아래를 하는 조건이 두가지이기 때문에 불필요한 elseif를 작성할 필요가 없다. 과감하게 삼항연산자를 이용해서 score가 5점이상이라면 엄지척을 아니라면 엄지다운을 리턴하는 것을 작성하면 Good Code와 같이 나오게된다.(불필요한 로컬변수와 if, else if는 필요가 없다.)
// Ternary Operator
// x Bad Code 💢
function getResult(score) {
let result;
if (score > 5) {
result = '👍';
} else if (score <= 5) {
result = '👎';
}
return result;
}
// 불필요한 else if
// Good Code✨
function getResult(score) {
return score > 5 ? '👍' : '👎';
}
다음으로 Nullish coalescing operator에 대해서 알아보면
전달받은 text 인자가 있다면 바로 할당을 하고 null이거나 undefined이면 nothing to display라는 문구를 출력하라는
Bad Code가 있다.
여기서 변동이 가능한 let이라는 변수를 선언한 것, 지저분한 if문을 이용한 것,
// Nullish coalescing operator
// x Bad Code 💢
// Default parameter is only for undefined
function printMessage(text) {
let message = text;
if (text == null || text == undefined) {
message = 'Nothing to display';
}
console.log(message);
}
nullish-coalescing을 이용해서 깔끔하게 작성하면
동일한 함수에서 text가 있다면 그대로 쓰고 text가 없는 경우에는
'Nothing to display'를 출력하도록 할 것이다.
그래서 각각 Hello undefined null로 출력을 해보면 Helo일 때는 문구가 그대로 출력이 되고
undefined일 경우와 null일 경우에는 Nothing to display를 출력한다.
// Good code
function printMessage(text) {
const message = text ?? 'Nothing to display';
console.log(message);
}
printMessage('Hello');
printMessage(undefined);
printMessage(null);
만약에 함수에서 인자에 디폴트값을 설정하면 text값을 지정하지 않는다면 'Nothing to display'출력하도록 만들어 줄 수 있다. 아래와 같은 코드를 실행하게 되면 Hello와 undefined은 Nothing to display를 출력하고 null은 그대로 null이 출력된다. 이처럼 디폴트 파라미터인 경우에는 undefined인 경우에만 할당이 된다.
null로 명확하게 지정하거나 값이 있는 경우에는 해당이 되지 않는다.
// 💢 Default parameter is only for undefined
function printMessage(text = 'Nothing to display 😀') {
console.log(text);
}
printMessage('Hello')
printMessage(undefined)
printMessage(null)
nullish-coalescing같은 경우에는 leftExpr ?? rightExpr 이렇게 나타나있으면 왼쪽코드가 null이거나 undefined경우에만 오른쪽코드가 실행되는 구조이다.
이것과 비슷한 logical or operator || 가 있다. leftExpr || rightExpr 이렇게 나타나 있고 이 경우는 leftExpr이 falsy인 경우에만 rightExpr이 실행이 된다.
falsy는 undefined null도 falsy에 해당하고 false도 falsy에 해당한다. 숫자 0과 -0도 falsy에 해당하고NaN도 falsy에 해당한다. '' "" ``도 falsy에 해당한다.
아래코드를 보면 undefined와 null 0 '' 모두 Nothing to display가 출력이 되고 Hello만 Hello문구가 출력이된다.
// Logical OR operator ||
function printMessage(text) {
const message = text || 'Nothing to display 👍';
console.log(message);
}
printMessage('Hello');
printMessage(undefined);
printMessage(null);
printMessage(0);
printMessage('');
여기서 보면 leftExpr과 rightExpr 둘다 expression인데 함수를 호출해서 첫번째가 실행되어서 실행된 값이 null이거나 undefined이라면 두번째 있는 fetchFromServer()이 실행이 되어서 결과값이 result에 할당이 된다.
이렇게 코드를 실행해서 실행된 값을 할당할 때도 이용이 된다.
const result = getInitialState() ?? fetchFromServer();
console.log(result);
funtion getInitialState() {
return null;
}
function fetchFromServer() {
retun 'Hiya from💥';
}
다음으로 Object Destructuring에 대해서 알아보면
아래와 같은 Bad Code가 있다. displayPerson이라는 함수는 Person을 인자로 받아서 필요한 person의 이름 나이를 호출하고 있다. 딱 봐도 반복적으로 쓰이고 있기 때문에 나쁜 코드이다.
const person = {
name: 'Julia',
age: 20,
phone: '0107777777',
};
// ✔ Bad Code 😒
function displayPerson(person) {
displayAvatar(person.name);
displayName(person.name);
displayProfile(person.name, person.age);
}
반복을 줄이고자 함수안에서 name과 age라는 변수를 설정할 수도 있는데 person.의 개수는 작아지기는 했지만 여전히 person.이 반복되어지고 보기에도 코드의 양이 늘어난 것을 볼 수 있다.
// ✔ Bad Code 😒
function displayPerson(person) {
const name = person.name;
const age = person.age;
displayAvatar(name);
displayName(name);
displayProfile(name, age);
}
이제 Object destructuring을 이용하게 되면 person이라는 오브젝트 안에있는 name을 변수에 할당하고 age값을 할당해서 쓴다. person.은 반복되어질 필요가 없고 name age로 간단하게 쓸 수 있다.
// Good Code💥
function displayPerson(person) {
const {name, age } = person;
displayAvatar(name);
displayName(name);
displayProfile(name, age);
}
참고: https://www.youtube.com/watch?v=BUAhpB3FmS4
'JavaScript > DreamCoding' 카테고리의 다른 글
JavaScript tip3 (0) | 2021.08.04 |
---|---|
JavaScript tip2 (0) | 2021.08.04 |
class 예제 & 콜백 함수 재정리 (0) | 2021.08.03 |
boolean과 && 연산자 (0) | 2021.08.03 |
함수 정의, 호출, 콜백함수 (0) | 2021.08.03 |