자바스크립트 && 연산자 및 optional Chaining,

김현진·2020년 7월 16일
0

자바스크립트에서 어떤객체에 값이 존재하는지 확인하는데 &&(and연산자) 및 optional Chaining이 있다.

예제를 살펴보면서 파악을 해보겠습니다.(예제는 MDN에서 가져왔습니다.)

ex)

const customer = {
  name : 'Carl',
  details: {
    age: 82,
    location: 'Seoul'
  }

}

위의 객체에서 location의 값이 있는지 확인 후 있다면 변수에 담고 없다면 undefined를 변수에 담아보겠습니다.(유용한 거 같아 까먹기전에 정리를 해야겠다고 마음먹었다.ㅋ)

방법1)

let customer = customer.details && customer.details.location; // Seoul;
customer객체에 details가 있고 그리고 customer.details.location이 있는경우 
customer변수에 customer.details.location 값이 들어간다.

만약 앞에 내용이 참이고 뒤의 내용이 거짓일경우 변수에는 undefined가 들어간다.

let customer = customer.details && customer.details.address;// undefined

둘다 거짓일 경우도 물론 undefined가 들어간다.

방법2)
optional Chaining 

약간 헷갈리기는 하지만 정리를 잘해보자!


방법1과 마찬가지로 객체에 location이라는 키가 있는지 확인 후 있다면 변수에 담을것이고 없으면 undefined를 담을 것이다.

일단 깊이가 1인 것부터 연습

let customer = customer?.defails // {age: 82, location: "Seoul"}//
let customer1 = customer?.adderss // undegfined

깊이가 2인거 연습

let customer = customer?.details?.location // Seoul
let customer = customer?.details?.address // undefined

옵셔널 체이닝 방식은 깊이를 들어갈때마다 ?. 를 붙여 확인을 하면되 코드의 길이를 훨씬줄여준다.

객체?.키?(깊이1).키?(깊이2).키(깊이3) 이런식으로 확인하면 됩니다. (물음표 다음 온점)

profile
기록의 중요성

0개의 댓글