본문 바로가기

개발/JavaScript

[JS] Optional chaining

Optional Chaining

const result = {
  status: 'OK',
  data: {
	  id: 1,
    title: 'title'
	}
}

console.log(result.data?.title) // title or undefined
console.log(result.data.title?.replace('e', 'a')) // titla or undefined

왼쪽이 null or undefined인 경우는 동작하지 않는다.

값이 존재하는지 체크 후 ?. 뒤의 코드를 실행

 

nullish coalescing operator

console.log(result.data.content ?? '없음') // 없음

왼쪽이 null or undefined인 경우 ?? 뒤의 값을 적용