[모던 JS 튜토리얼] 2.12. nullish 병합 연산자 ‘??’

승연·2023년 11월 17일
0
post-thumbnail

짧은 문법으로 여러 피연산자 중 그 값이 ‘확정되어있는’ 변수를 찾을 수 있음

a ?? b

  • anull도 아니고 undefined 도 아니면 a
  • 그 외는 b
<script>
      
      let firstName = null;
      let lastName = null;
      let nickName = '한승연';

      alert(firstName ?? lastName ?? nickName ?? '익명의 사용자'); //한승연 

   </script>

→ 값이 정해진 변수를 쉽게 찾아낼 수 O

2.12.1. ‘??’ 과 ‘||’의 차이

  • || 는 첫 번째 truthy 값 반환
  • ?? 는 첫 번째 정의된 (defined) 값 반환

null, undefined, 0 구분 지을 때 중요

<script>
      
      let height = 0;
      alert(height || 100);   //100 (height에 할당된 0을 falsy로 취급)
      alert(height ?? 100);   //0 (height에 0이 할당되어 defined로 생각)

   </script>

2.12.2. 연산자 우선순위

??는 우선순위가 낮은 편이므로 사용 시 괄호 추가

profile
앙녕항셍용

0개의 댓글