Posts

[JS] 도움이 되는 연산자

목차4

?. (Optional Chaining)

Optional Chaining은 객체 내부의 속성에 접근할 때 속성이 존재하지 않아서 TypeError가 발생하는 것을 방지하기 위해 도입된 연산자다. 만약 속성이 존재하지 않는다면 undefined를 반환하고, 그렇지 않은 경우에는 해당 속성에 접근한다.

코드
const user = {
  name: 'John',
  address: {
    city: 'Seoul',
    country: 'South Korea'
  }
};

console.log(user.address?.city); // 'Seoul'
console.log(user.address?.state); // undefined

&& (Logical AND)

AND 연산자는 왼쪽 피연산자와 오른쪽 피연산자 모두가 true일 경우에만 true를 반환한다. 따라서, 왼쪽 피연산자가 false일 경우에는 오른쪽 피연산자를 검사하지 않는다. 주로 조건문에서 사용된다.

코드
const x = 5;
const y = 10;

if (x > 0 && y > 0) {
  console.log('Both x and y are positive');
}

|| (Logical OR)

OR 연산자는 왼쪽 피연산자와 오른쪽 피연산자 중 하나라도 true이면 true를 반환한다. 따라서, 왼쪽 피연산자가 true일 경우에는 오른쪽 피연산자를 검사하지 않는다. 주로 기본값 설정 등에 사용된다.

코드
const name = '';
const displayName = name || 'Anonymous';

console.log(displayName); // 'Anonymous'

?? (Nullish Coalescing)

Nullish Coalescing은 변수가 null 또는 undefined인 경우에 대해 기본값을 설정하는 연산자다. || 연산자와 유사하지만, null과 undefined를 구별하여 처리한다.

코드
const name = null;
const displayName = name ?? 'Anonymous';

console.log(displayName); // null

반응형