완로그
article thumbnail

⏳ 2023. 5. 8. - 2023. 5. 14.

 

<javascript />
// 선택적 체이닝(Optional Chaining) const obj = {}; console.log(obj.name); // undefined const isNull = null; const isUndefined = undefined; // console.log(isNull.name); ❌ error // console.log(isUndefined.name); ❌ error console.log(isNull?.name); // undefined console.log(isUndefined?.name); // undefined

객체 데이터의 없는 속성을 점 표기법으로 불러오면 undefined이다.

그러나 null이나 undefined는 점 표기법을 사용할 수 없어 에러가 발생한다.

그럴때 사용할 수 있는 것이 선택적 체이닝이다.

 

다음과 같은 상황에서 유용하나, 선택적 체이닝은 꼭 필요한 상황이 아니면 사용하지 않는걸 권장한다.

<javascript />
const userA = { name: "HEROPY", age: 85, address: { country: "Korea", city: "Seoul", }, }; const userB = { name: "Neo", age: 22, }; function getCity(user) { return user.address?.city || "주소 없음"; } console.log(getCity(userA)); // "Seoul" console.log(getCity(userB)); // "주소 없음"
profile

완로그

@완석이

프론트엔드 개발자를 꿈꾸는 완석이의 일기장입니다.