강의 출처 : The Complete JavaScript Course 2022 Jonas (Udemy)
Section 9 - Data Structures, Modern Operators and Strings
Use Any data type, return ANY data type
console.log(3 || 'Jonas'); // 3
console.log('' || 'Jonas'); // Jonas '' 가 falsy value 이므로
console.log(true || 0); // true
console.log(undefined || null); // 앞에 있는게 falsy라 뒤의 값 null 출력
console.log(undefined || 0 || '' || 'Hello' || 23 || null); // Hello
const guests1 = restaurant.numGuests ? restaurant.numGuests : 10;
console.log(guests1); //10
short circuiting 이용하기 (더 간단한 방식)
const guests2 = restaurant.numGuests || 10;
console.log(guests2); // 10
console.log('-----AND-----');
console.log(0 && 'Jonas'); //0 falsy value 인 0 을 바로 return 한다.
console.log(7 && 'Jonas'); // Jonas
console.log('Hello' && 23 && null && 'jonas'); // null
if (restaurant.orderPizza) {
restaurant.orderPizza('mushrooms', 'spinach');
} // mushrooms ['spinach']
restaurant.orderPizza && restaurant.orderPizza('mushrooms', 'spinach'); // mushrooms ['spinach']
요약)
A || B : A가 아니면 B
A && B : A가 맞으면 B
기존의 코드
restaurant.numGuests = 0;
const guests = restaurant.numGuests || 10;
console.log(guests); // 10; 0 is falsy value
the Nullish Coalescing Operator로 문제 해결하기
->find nullish value instead of falsy value
참고) nullish value : null and undefined (NOT 0 or '')
const guestCorrect = restaurant.numGuests ?? 10;
console.log(guestCorrect); // 0
const rest1 = {
name: 'Capri',
//numGuests: 20,
numGuests: 0,
};
const rest2 = {
name: 'La Piazza',
owner: 'Giovanni Rossi',
};
rest1.numGuests = rest1.numGuests || 10;
rest2.numGuests = rest2.numGuests || 10;
rest1.numGuests ||= 10;
rest2.numGuests ||= 10;
rest1.numGuests ??= 10;
rest2.numGuests ??= 10;
//rest1.owner = rest1.owner && '<ANONYMOUS>';
//rest2.owner = rest2.owner && '<ANONYMOUS>';
rest1.owner &&= '<ANONYMOUS>';
rest2.owner &&= '<ANONYMOUS>';
console.log(rest1.owner); //undefined why? rest1.owner 값이 존재하지 않으므로!
console.log(rest2.owner); //<ANONYMOUS> rest2.owner 값이 존재하므로!
console.log(rest1.numGuests); //20 //0
console.log(rest2.numGuests); //10 //10