[JS] Syntax | 15. Optional chaining - 속성 존재여부 확인하기

2025. 4. 4. 12:14·Language/JavaScript

JavaScript에서 객체에 대한 조건문을 작성할 때, 특정 속성값이 있는지의 여부가 중요하게 작용할 때가 있습니다.

const user1 = {
    'name': 'Jhon',
    'age': 20,
    'membership': 'plus',
}

const user2 = {
    'name': 'Mary',
    'age': 20,
}

// user2는 membership을 속성값으로 가지지 않기 때문에 에러가 발생합니다
if (user1.membership === 'plus' && user2.membership === 'plus'){
    console.log('all of them have plus membership');
}

이 경우, 해당 객체에 속성값이 존재하는지 먼저 확인한 수 조건문을 작성해야 합니다.

// membership의 존재 여부를 파악합니다.
if (user2.membership === undefined) {
    console.log("there is no membership");
} else {
    console.log(user2.membership);
}

// 속성값을 다룰 때는 조건 연산자를 이용한 처리도 가능합니다.
console.log(user2.membership && user2.membership.splice(2));

하지만 속성 이름이 길어지고 객체의 계층이 깊어질 수록 코드도 늘어나기 때문에, optional chaining(?) 구문을 통해 간단하게 나타내는 것이 좋습니다.

// ?가 붙은 속성값이 존재한다면 이후 접근을 처리하고, 그렇지 않으면 undefined를 반환합니다.
console.log(user2.membership?.splice(2));
728x90

'Language > JavaScript' 카테고리의 다른 글

[JS] Syntax | 17. 예외처리  (0) 2025.04.06
[JS] Syntax | 16. 구조분해(Destructuring)  (0) 2025.04.05
[JS] Syntax | 14. 계산된 속성명 (computed property name)  (0) 2025.04.04
[JS] Syntax | 13. Spread - 배열 또는 객체 분해하기  (0) 2025.04.02
[JS] Syntax | 12. Arrow function  (0) 2025.03.31
'Language/JavaScript' 카테고리의 다른 글
  • [JS] Syntax | 17. 예외처리
  • [JS] Syntax | 16. 구조분해(Destructuring)
  • [JS] Syntax | 14. 계산된 속성명 (computed property name)
  • [JS] Syntax | 13. Spread - 배열 또는 객체 분해하기
Rayi
Rayi
  • Rayi
    아카이브
    Rayi
  • 전체
    오늘
    어제
    • 분류 전체보기 (276)
      • CS (40)
        • CV (2)
        • PS (34)
      • Reveiw (18)
        • Paper (18)
        • Github (0)
      • ML (8)
        • Pytorch (5)
      • Language (59)
        • Python (8)
        • JavaScript (32)
        • TypeScript (16)
        • C++ (3)
      • IDE (12)
      • Git (13)
      • Frontend (77)
        • React (8)
        • ReactNative (6)
        • SolidJS (20)
        • CSS (12)
      • Backend (44)
        • DB (18)
        • Node.js (11)
      • UI (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    nodejs
    postgresql
    ps
    ML
    python
    DB
    backend
    Express
    ReactNative
    deploy
    vscode
    Git
    CSS
    Three
    expo
    modal
    SOLID
    CS
    js
    CV
    react
    figma
    review
    frontend
    PyTorch
    mongo
    GAN
    PRISMA
    ts
    API
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[JS] Syntax | 15. Optional chaining - 속성 존재여부 확인하기
상단으로

티스토리툴바