• Logical Assignment
Logical Assignment는 ES2021 버전부터 추가된 문법으로
논리 연산과 변수 할당을 함께 수행합니다.
먼저 Logical And Assignment부터 살펴보자면
// Logical And Assignment x &&= y
• x가 truthy일 때 y의 값이 x로 할당됩니다.
( 즉 x && (x = y), x = x && y 와 같은 의미입니다. )
Logical Assignment을 사용하지 않던 과거의 코드입니다.
let x = 1; let y = 0; if (x) { x = 'Seoul Mayor'; console.log(x); // expected output : Seoul Mayor } if (y) { y = 'Seoul Mayor'; console.log(y); // expected output : 0 }
let x = 1; let y = 0; x = x && 'Seoul Mayor'; console.log(x); // expected output : Seoul Mayor y = y && 'Seoul Mayor'; console.log(y); // expected output : 0
위의 예시들의 코드는 Logical And Assignment 문법을 사용하면
더욱 간결하게 수정할 수 있습니다.
let x = 1; let y = 0; x &&= 'Seoul Mayor'; console.log(x); // expected output : Seoul Mayor y &&= 'Seoul Mayor'; console.log(y) // expected output : 0
연산자 OR(||)과 ES2020부터 추가된 Nullish(??)를 사용하는
문법 역시 존재하며, 각각 Logical Or Assignment와 Logical Nullish Assignment라고 부릅니다.
사용법은 Logical And Assignment와 동일하며 간단한 예시로 아래와 같이 사용할 수 있습니다.
const kingPork = { height : 173, weight : 0 }; kingPork.height ||= 193; console.log(kingPork.height); // expected output : 173 kingPork.weight ||= 73; console.log(kingPork.weight); // expected output : 73 kingPork.morningExercise ??= 'fail'; console.log(kingPork.morningExercise); // expected output : fail
'JavaScript > ES6+' 카테고리의 다른 글
[JavaScript] var, let, const는 언제 어떻게 사용해야할까? (0) | 2021.10.05 |
---|