3.7 JavaScript 선택적 체이닝(Optional Chaning)

지구·2023년 7월 18일
0

JavaScript

목록 보기
12/30
const user = {}

console.log(user.name) // undefined
const user = null

console.log(user.name) // 에러 발생
const user = undefined

console.log(user.name) // 에러 발생

null 이나 undefined 또는 객체에 없는 변수를 점표기법으로 속성을 조회할 수 없는 상황에서는 선택적 체이닝을 사용할 수 있다.

선택적 체이닝(Optional Chaning)

const user = null

console.log(user?.name) // undefined

에러가 출력됐던 것이 에러 없이 undefined가 출력된 것을 볼 수 있다.

선택적 체이닝 활용

const userA = {
	name: 'JIGU',
  age: 85,
	address: {
		country: 'Korea',
		city: 'Seoul'
	}
}

const userB = {
	name: 'Neo',
	age: 22
}

function getCity (user) {
	return user.address.city
}

console.log(getCity(userA))
console.log(getCity(userB))

// 결과
// Seoul
// 에러 발생

userA에는 address에 city가 있지만 userB에는 없어서 에러가 발생한다.

function getCity (user) {
	return user.address?.city
}

console.log(getCity(userA))
console.log(getCity(userB))

// 결과
// Seoul
// undefined

선택적 체이닝을 이용해서 에러가 발생하지 않도록 한다.

function getCity (user) {
	return user.address?.city || '주소 없음.'
}

console.log(getCity(userA))
console.log(getCity(userB))

// 결과
// Seoul
// 주소 없음.

OR 연산자를 활용해서 OR 연산자 왼쪽 값이 falsy 데이터이므로 오른쪽 값인 '주소 없음.'을 반환한다.

profile
프론트엔트 개발자입니다 🧑‍💻

0개의 댓글