Optional chaining operator '?' & Nullish coalescing operator '??'

Janet·2023년 1월 9일
0

JavaScript

목록 보기
15/26

🔶 Optional chaining operator(옵셔널 체이닝 연산자) ‘?’과 Nullish coalescing operator(nullish 병합 연산자) ‘??’


🔷 .? 중첩 Object에서 .이 두 개인 경우 활용 가능한 Optional chaining 문법

const user = {
    name : 'tom',
    age : 20
};

console.log(user.name) // tom
console.log(user?.name) // tom
  • 위와 같이 여러 문자, 숫자 등을 한 변수에 Object 형태로 변수 선언한 경우
    • 해당 오브젝트 자료에서 원하는 데이터를 뽑고 싶을 때 . 을 사용 한다. 예시 ⬇️
      • console.log(user.name) // tom
    • ?. 을 사용하여도 결과는 같은데, ?. 를 기준으로 왼쪽 데이터가 비어있으면(null 혹은 undefined), ?.의 오른쪽 데이터 연산은 하지 않고 결과값으로 undefined 를 남긴다. 이를 Optional chaining 연산자 라고 부른다.
    • 아래와 같은 경우는 ?. 왼쪽 데이터가 존재하기에 tom이라는 결과값이 도출된다. 예시 ⬇️
      • console.log(user?.name) // tom
  • 그러나 보통 이 문법은 중첩된 object 자료에서 데이터를 뽑을 때 reference error 없이 안전하게 뽑을 수 있다.
    const user = {
    	name : 'tom',
    	age : {value : 20}
    };
    
    console.log(user.age.value) // 20
    console.log(user.sex) // undefined
    console.log(user.sex.value) // error
    console.log(user.sex?.value) // undefined
    • console.log(user.age.value) // 20
    • cf. 중첩된 데이터가 아닌 경우 (. 을 1개만 쓰는 경우)에는 굳이 Optional chaining 연산자 를 쓰지 않아도 결과값이 undefined 이다. 따라서 ?.는 중첩된 object 자료에서 사용함. 아래 예시는 object에 없는 성별(sex) 데이터를 뽑으려할 때의 연산 결과이다. console.log(user.sex) // undefined console.log(user.sex.value) // error (Uncaught TypeError: Cannot read properties of undefined (reading ‘value’)
      • 하지만 ?. 연산자를 쓸 경우? console.log(user.sex?.value) // undefined

🔷 ?? Nullish coalescing 연산자

  • undefined, null 과 같은 Nullish 값을 검사하는 연산자

  • 아래 예시처럼 user라는 변수가 undefined 혹은 null인 경우 ‘로딩중!’라는 결과값을 보여 줌.

    const user = {
        ...data들
    };
    
    console.log(user ?? 'Loading...') // Loading...

🔷 ?? 과 ||의 차이?

  • undefined, null 과 같은 Nullish 값을 검사하는 연산자: ??

  • 0, "", false, undefined 등과 같은 falsy 값을 전부 검사하는 연산자: ||

    const a = false || "눈누";
    console.log(a) // "눈누"
    
    const b = false ?? "난나";
    console.log(b) // false
    
    const c = undefined ?? null ?? "랄랄",
    console.log(c) // "랄랄"
profile
😸

0개의 댓글