Javascript/vanilla

옵셔널 체이닝

브라더 코드 2022. 6. 14. 17:07

?. 

 

이 문법은 객체의 값에 접근할 때 사용한다.

간단하다.

 

?. 왼쪽이 null, undefined이면 

?. 오른쪽을 실행하지 않고 undefined를 리턴한다.

 

반대로

?. 왼쪽이 null, undefined가 아니면

?. 오른쪽을 실행한다.

 

let human = {
    age: 30,
    address: "korea",
    name: {
        lastName: "park",
    }
}

console.log(human.job); // undefined
console.log(human.job.salary); // error: Cannot read properties of undefined
console.log(human.job?.salary); //undefined
console.log(human.name?.lastName); // park