Javascript - Optional chaining

Enjoywater·2020년 9월 29일
0

TIL

목록 보기
24/33
post-thumbnail

Optional chaining

Optional chainingES2020에서 새롭게 추가된 문법으로, ?.를 사용하여 객체의 속성값에 접근할 수 있게 해주는 문법이다.

참조하는 대상이 null / undefined가 아니라면, 속성에 대한 접근이 가능하다.
만약 null / undefined라면 undefined를 반환한다.

const user = { name: { first: "Water", last: "Enjoy" } }

user 객체 속 객체에 접근하는 상황으로 예를 들어보면,

console.log(user.name.first)
// 결과값 => "Water"

console.log(user.address.street)
// 결과값 => TypeError: Cannot read property 'street' of undefined

위와 같이 결과값이 나오게 된다.

TypeError의 발생을 막기 위해서는 && 연산자를 포함시켜 값을 출력해야만 한다.

console.log(user.address && user.address.street)

// 결과값 => undefined

이때, Optional chaining의 사용으로 코드를 간결하게 줄일 수 있다.

console.log(user.address?.street)

// 결과값 => undefined

해당 코드는 user 객체address라는 객체가 있다면 street를 출력한다고 풀이가 될 수 있다.
Optional chaining의 사용은 method를 사용할 때 유용하게 쓰일 수 있다.

const age = null;

console.log(age.map( (el) => el ) )
// 결과값 => TypeError: Cannot read property 'map' of null

console.log(age?.map( (el) => el ) )
// 결과값 => undefined
profile
블로그 이전 👉🏻 enjoywater.tistory.com

0개의 댓글