옵셔널 체이닝(optinal chaining / ?.)

BM1201·2024년 3월 25일

JavaScript

목록 보기
2/4
post-thumbnail

형태
?.

역할
객체 내의 key에 접근할 때 그 참조가 유효한지 아닌지 직접 명시하지 않고 접근할 수 있는 연산자입니다. ?. 앞의 평가대상이 만약 nullish ( undefined 또는 null ) 일 경우 평가를 멈추고 undefined를 반환합니다.

사용법
1. undefined 체크시 사용

const user: {
	name: ‘coding’,
}

console.log(user?.name); => coding
console.log(user?.age); => undefined
  1. nullish연산자와 함께 사용하여 기본값 부여
const user: {
	name: ‘coding’,
}

const address = user.info?.address ?? 'default'; => default
  1. 대괄호 표기법, 함수호출, 배열에서도 사용가능
//대괄호 예시
const user: {
	name: ‘coding’,
}
const key = "name";
const name = user?.[key];

//함수예시
const test: {
	method : function() {
    	console.log('test');
    }
}

const res = test.method?.();// method의 value가 함수가 아니라면 타입에러 발생함

//배열예시
const test = [1,2,3,4,5]
console.log(arr?.[10]); => undefined

주의사항
1. 존재하지 않아도 괜찮은 대상에만 적용

//user라는 객체에 info와 age가 필수값이 아니라면 두번째 방식으로 사용해야합니다.
console.log(user?.info?.age); //이렇게 사용시 user객체도 필수값이 아님 
console.log(user.info?.age);
  1. ?.(optional chaining)앞에 오는 변수는 선언이 되어 있어야함 선언되지 않은 변수에 사용하면 에러발생
profile
개발자의 기록하는 습관

0개의 댓글