👉 JavaScript에서 세 개의 피연산자를 취할 수 있는 유일한 연산자이며 보통 if 명령문의 단축 형태로 쓰인다.
condition ? exprIfTrue : exprIfFalse
condition(조건)이 true이면 exprIfTrue가 실행되고, false이면 exprIfFalse가 실행된다.
🙆 예시
일반적인 if else 구문
if(replyVal.length > 0) {
postBtnText.style.color = '#009DF9';
} else {
postBtnText.style.color = '#B9DFFC';
}
위의 구문은 다음과 같이 삼항연산자로 표현 될 수 있다.
replyVal.length > 0 ? postBtnText.style.color = '#009DF9': postBtnText.style.color = '#B9DFFC');
보다시피 코드가 훨씬 간결해 진 것을 확인할 수 있다.
👏 다양한 활용 예제
다중 삼항 평가도 가능하다 ( 단! 조건 연산은 우측부터 그룹핑된다. )
var firstCheck = false,
secondCheck = false,
access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted";
console.log( access ); // logs "Access granted"
var condition1 = true,
condition2 = false,
access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false");
console.log(access); // logs "true false"
📌 참고 : 괄호는 필수는 아니며 기능에 영향을 주지 않는다. 결과가 어떻게 처리되는지 시각화하는 데 도움이 된다.
참고자료
MDN, 삼항연산자