[JS] Syntax | 10. 병합연산자(??)

2025. 3. 23. 22:05·Language/JavaScript

JavaScript에서는 and(&&)와 or(||) 연산을 할 때 첫 번째 값에 무엇이 오느냐에 따라 출력값이 달라집니다.

operand 1 operand 2 AND OR
Truthy Truthy  operand 2 operand 1
Truthy Falsy operand 2 operand 1
Falsy Truthy operand 1 operand 2
Falsy Falsy operand 1 operand 2

그리고 이를 이용하여 특정 변수에 기본값을 지정하는 코드를 작성할 수도 있습니다.

const perhapsNull = null;

// perhapsNull이 false라면 'notNull'을, true라면 perhapsNull을 반환합니다.
const value = perhapsNull || 'notNull';

여기서 true / false 값이 아니라 null & undefined 여부만 확인하고 싶다면, 병합 연산자 ?? 를 사용하면 됩니다.

const value1 = null ?? 'javascript'; // 'javascript'
const value2 = [] ?? ['1']; // []

??의 경우 null & undefined만 판단하기 때문에, 첫 번째 피연산자가 falsy여도 null 이나 undefined가 아니라면 그대로 반환된다는 차이가 있습니다.

728x90

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

[JS] Syntax | 12. Arrow function  (0) 2025.03.31
[JS] Syntax | 11. rest parameter - 가변 변수 사용하기  (0) 2025.03.29
[JS] CommonJS & ES에 대해서  (0) 2025.03.21
[JS] Library | 02. Papaparse  (0) 2024.12.10
[JS] Library | 01. Superstruct  (0) 2024.08.25
'Language/JavaScript' 카테고리의 다른 글
  • [JS] Syntax | 12. Arrow function
  • [JS] Syntax | 11. rest parameter - 가변 변수 사용하기
  • [JS] CommonJS & ES에 대해서
  • [JS] Library | 02. Papaparse
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)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
Rayi
[JS] Syntax | 10. 병합연산자(??)
상단으로

티스토리툴바