본문 바로가기

Programming/Javascript

Javascript 조건(삼항) 연산자 / 널 병합 연산자 / 옵셔널 체이닝

반응형

 1. ? 조건(삼항) 연산자 (Conditional(ternary) operator)

 조건 연산자는 if 문을 대체할 수 있다.

 조건 연산자는 다음과 같이 사용된다.

condition ? exprIfTrue : exprIfFalse

 condition: 조건문으로 사용되는 표현식

 exprIfTrue: condition이 참(truthy)이면 실행되는 식

 exprIfFalse: condition이 거짓(falsy)이면 실행되는 식

 

예시로 다음과 같은 if문을 조건 연산자로 짧고 간결하게 변형 가능하다.

let result;
if(true){
    result = "참";
} else {
    result = "거짓";
}

// 위 if문을 조건 연산자로 변형
result = true ? "참" : "거짓";

 

2. ?? 널 병합 연산자 (Nullish coalescing operator)

널 병합 연산자를 사용하면 짧은 문법으로 null 또는 undefined의 경우에 기본값을 할당할 수 있다.

leftExpr ?? rightExpr

 널 병합 현사자는 leftExpr이 null 또는 undefined인 경우 rightExpr을 반환한다.

 

에시로 다음과 같은 문법을 널 병합 연산자로 변형 가능하다.

 

let result, a;
let b = "default";
if(a != null && a!= undefined){
    result = a;
} else {
    result = b;
}

// 위 if문을 널 병합 연산자로 변형
result = a ?? b;

 

 

3. ?. 옵셔널 체이닝 (Optional chaining)

 옵셔널 체이닝을 사용하면 해당 property가 없는 객체에 에러없이 안전하게 접근할 수 있다.
 옵셔널 체이닝을 사용하여 property가 없는 객체를 호출 시 undefined를 반환한다.
 객체 이외에도 배열, 함수에서도 사용이 가능하다.

다음과 같은 방법으로 사용된다.

obj?.prop;
obj?.[expr];
array?.[index];
func?.(args);

 

다음과 같이 에러가 발생하는 상황에서 옵셔널 체이닝을 사용한다면 에러가 발생하지 않는다.

let a = {};
cosole.log(a.name) // TypeError: Cannot read property 'name' of undefined

// 옵셔널 체이닝
console.log(a?.name) 
//result: undefined   에러가 발생하지 않는다.

 

참고: 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Optional_chaining

 

반응형