ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Section 11. 자바스크립트 옵셔널 체이닝
    자바스크립트 2023. 4. 7. 15:49

    유효하지 않을 수 있는 참조에 의한 문제들에 대해서 옵셔널 체이닝이 매우 유용하게 쓰일 수 있다.

     

    유효하지 않을 수 있는 참조에 의한 문제들

    네트워크 요청 등, 어떤 값이 들어올지 모르는 상황이 있다.

     

    에러가 발생하는 상황들은 다음과 같다

    // undefined로부터 값에 접근할 때
    let undefObj;
    console.log(undefObj.x);
    
    // null부터 값에 접근할 때
    let nullObj = null;
    console.log(nullObj.x);
    
    // 무효한 배열에 접근할 때
    let undefArry;
    console.log(undefArry[1]);
    
    // 존재하지 않는 함수를 호출할 때
    let noFunc = {}
    noFunc.func();

     

    또 이런 상황도 있다.

    결과에 prop3가 있다면 가져와야 하는 상황이다.

    // 최소 undefined
    // 최대 {prop1:{prop2:{prop3:'성공!'}}}
    // 까지 반환하는 함수
    const rand = () => Math.random() < 0.75;
    
    const notSure = () => rand() ? {
      prop1: rand() ? {
        prop2: rand() ? {
          prop3: rand() ? '성공!' : undefined
        } : undefined
      } : undefined
    } : undefined;
    console.log(JSON.stringify(notSure()));

    4분의 3확률로 true를 반환하는 함수에서 출력문을 여러번 시도해보니 할 때마다 결과가 다른 것을 볼 수 있다. 

     

    const result = notSure();
    console.log(JSON.stringify(result));
    
    // ⚠️ 바로 접근하려 할 시에는 실패시 에러
    console.log(result.prop1.prop2.prop3);

    마찬가지로 result에 notSure()을 할당했을때 만약에 prop3까지 다 가져왔다면 애러가 나지 않고 그렇지 않으면 애러가 날 수 있다. 즉, 출력문을 실행했을때 어떤 결과가 나올지 모르는 상황인 것이다. 

     

    이런 상황들에서 애러가 나서 프로그램이 종료가 되지 않게 하려면 어떻게 해야 할까?

     

    방법 1

    // 방법 1
    const result = notSure();
    
    if (result) {
      if (result.prop1) {
        if (result.prop1.prop2) {
          console.log(result.prop1.prop2.prop3);
        }
      }
    }

    만약 prop3까지 다 반환된 경우라면 성공! 이 출력되고 아니면 undefined가 출력된다. 프로그램이 멈추진 않는다.

     

    방법 2

    // 방법 2
    const result = notSure();
    
    console.log(
      result
      && result.prop1
      && result.prop1.prop2
      && result.prop1.prop2.prop3
    );

     

    방법 3

    // 방법 3
    const result = notSure();
    
    try {
      console.log(result.prop1.prop2.prop3);
    } catch {
      console.log(undefined);
    }

    방법 2와 방법 3도 마찬가지이다.

    방법1,2,3은 모두 옵셔널 체이닝이 없었을 때 애러를 피하는 방식이었다.

    ?. - 옵셔녈 체이닝 optional chaining 연산자

    • 호출 대상이 undefined 나 null 이어도 오류를 발생시키지 않는다. 대신 undefined를 반환한다.
    • 있을지 없을지 모르는 것으로부터 값을 읽거나 실행할 때 사용한다.
    // 옵셔널 체이닝을 사용한 방법
    const result = notSure();
    
    console.log(
      result?.prop1?.prop2?.prop3
    );

    역시 prop3까지 반환이 된 경우는 성공! 을 출력하고 아닌 경우에는 undefined가 출력된다. 

    엄청나게 간단해진 것을 볼 수 있다. 

     

Designed by Tistory.