본문 바로가기
🩵 React/학습 노트

[React🩵] ||(or연산자) ??(Nullish Coalescing 연산자)의 차이점

by 솔비님 2025. 2. 26.

01.  || (OR 연산자) vs ?? (Nullish Coalescing 연산자)의 차이점

  • 공통점: 둘다 기본값을 설정하는데 사용된다
  • 차이점:
    * ||(OR 연산자): Falsy**값이면 오른쪽 값을 사용한다
    * ??(Nulllish Coalescing 연산자): null 또는 underfined일 때만 오른쪽 값 사용

**Falsy값: false, 0, "", null, undefined, NaN

 

 

 

02.  활용 예시

const displayPreferences = (preference) => {  
    const textLength = preference.textLength || 50;  // `||` 사용
    console.log("1 => ", textLength);

    const itemsPerPage = preference.itemsPerPage ?? 10;  // `??` 사용
    console.log("2 => ", itemsPerPage);
};

const userPreference = {  
    textLength: 0,   // `0` (Falsy 값)
    itemsPerPage: null, 
};

displayPreferences(userPreference);

 

✅ 해당 코드에서 userPreference.textLength = 0

👉🏻 0 || 50 ⇢ 0이 Falsy이므로 오른쪽 값인 50이 사용됨

 

 preference.itemPerPage = null

👉🏻 null ?? 10 이므로 오른쪽 값인 10이 사용됨

 

 

 

03.  언제 사용해야 할까?

사용 목적 추천 연산자
기본값을 설정하되, 0, "", false도 기본값으로 대체하고 싶다면 ||(OR 연산자)
null 또는 undefined일 때만 기본값을 설정하고 싶다면 ?? (Nullish Coalescing)

 

✔ 숫자 0도 유효한 값으로 인정해야 하면 ?? 사용
✔ 모든 Falsy 값을 대체해야 하면 || 사용

'🩵 React > 학습 노트' 카테고리의 다른 글

[React🩵] useState  (0) 2025.02.28
[React🩵] Props  (0) 2025.02.27
[React🩵] id와 className  (0) 2025.02.27
[React🩵] Promise  (0) 2025.02.26
[React🩵] 구조 분해 할당(Destructuring)  (0) 2025.02.25