optional chaining

2024. 6. 13. 15:19

optional chaining(?.)은 객체의 속성이나 함수를 사용할 때, 그 값이 null이나 undefined라면 에러를 발생하는 것 대신에 undefined를 리턴하게 해 준다.

 

const player = {
    name : "동혁",
    class : "전사",
    inventory: {
        potion : 100
        gold : 500
    }
}

예를 들어 위 코드의 player 객체에서 인벤토리에 있는 골드에 접근하려면

 

const potionNum = player.inventory && player.inventory.potion;

player 객체에 inventory가 있는지부터 검사해야 한다.

 

 

하지만 optional chaning을 사용하면 코드를 간단하게 작성할 수 있다.

const potionNum = player.inventory?.potion;

이 코드는 아래 코드와 같은 동작을 한다.

const potionNum = player.inventory === null || player.inventory === undefined ? undefined : player.inventory.potion

 

 

메소드의 경우에도 동일하게 사용할 수 았다.

아직 구현을 못했거나, 사용자 측에서 사용할 수 없게 만든 메소드 들을 처리할 때 유용하다.

 

 

const result = api.method?.();

객체의 속성에서 사용할 때와 마찬가지로 메소드를 찾을 수 없을 경우 에러 대신에 undefined를 반환한다.

 

 


 

참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Optional_chaining

BELATED ARTICLES

more