[JS] Short Circuiting, The Nullish Operator(??), Logical Assignment Operators

Hyodduru ·2021년 12월 9일
0

JavaScript

목록 보기
33/60
post-thumbnail

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

Section 9 - Data Structures, Modern Operators and Strings

Short Circuiting(&& and ||)

or(||) short circuiting

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

and(&&) short circuiting

console.log('-----AND-----');
console.log(0 && 'Jonas'); //0  falsy value 인 0 을 바로 return 한다.
console.log(7 && 'Jonas'); // Jonas
console.log('Hello' && 23 && null && 'jonas'); // null

Practical example

 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

The Nullish Coalescing Operator(??)

기존의 코드

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

Logical Assignment Operators

const rest1 = {
  name: 'Capri',
  //numGuests: 20,
  numGuests: 0,
};
const rest2 = {
  name: 'La Piazza',
  owner: 'Giovanni Rossi',
};

OR assignment operator

rest1.numGuests = rest1.numGuests || 10;
rest2.numGuests = rest2.numGuests || 10;
rest1.numGuests ||= 10;
rest2.numGuests ||= 10;

nullish assignment operator(null or undefined)

rest1.numGuests ??= 10;
rest2.numGuests ??= 10;

AND assignment operator

//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
profile
꾸준히 성장하기🦋 https://hyodduru.tistory.com/ 로 블로그 옮겼습니다

0개의 댓글