[실전 자바스크립트]optional chaining

주수호·2021년 2월 21일
0

[javascript]

목록 보기
10/10

optional chaining

const person = null;
const name = person.name; //이렇게 없는 값을 참조하기 때문에, runtime error발생

//하지만 검사로직을 추가함으로써 이를 해결 할 수 있다.
const person = null;
const name = person && person.name; //논리연산자를 활용해서 검사하기 null은 false라면 뒤의 값이 들어가지도 않겠지.
const name1 = person?.name; //optional chaining을 통한 검사 방식 ?.를 활용하여, person을 검사해준다. 해당코드는 아래와 같다.
const name = person === null || person === undefined ? undefined : person.name; // null 또는 undefined에 대한 검사가 진행된다.

함수를 호출시에 optional chaining

const person = {
	getName: () => 'abc',
};
const name = person.getName?.(); //함수 호출시에 괄호를 열기전에 ?.을 활용하면 된다. getName이라는 함수가 person이라는 object안에 명시되어져 있기 때문에, abc가 로그에 출력이 된다.
console.log(name); // abc 만약에 함수가 없다는 상황이라면? undefined가 출력된다.

//함수를 사용할 때 또한 optionalchaining을 활용 할 수 있고, undefined검사가 가능해 진다.

함수 호출시 optionalchaining의 유용성

function loadData(onComplete) {
	console.log('loading...');
  	onComplete?.(); //함수를 받아서 매개변수로 호출시에 유용하다
}
loadData(); // 함수 호출

배열아이템의 접근시에 optionalchaining의 유용성

const person = { friends: null, mother: null };

const firstFriend = person.friends?.[0]; //optional chaining으로 undefined를 할당 받을 수 있다.

const prop = 'name';
const name = person.mother?.[prop]; //객체에 속성값을 입력할 때에도 활용이 가능하다. mother라는 객체에 속성값을 추가하였다.

optional chaining은 검사단계가 많을수록 유용하다

//사용안했을 때
const name =
      person &&
      person.friends &&
      person.friends[0] &&
      person.friends[0].mother &&
      person.friends[0].mother.name; // 이렇게 &&연산자로 하나씩 작성해주어야 하는 것을

const name2 = person?.friedns?.[0]?.mother?.name; // 심플하게 표현이 가능하다.

optional chaining은 nulish coalescing과 연동하기에 좋다.

const person = {};
const name = person?.friends?.[0]?.mother?.name ?? 'default name';
//nulish coalescing
profile
항상 준비하는 엔지니어

0개의 댓글