자바스크립트 기초
삼항 연산자
tturbo0824
2021. 7. 17. 15:08
삼항 조건 연산자는 JavaScript에서 세 개의 피연산자를 취할 수 있는 유일한 연산자로 보통 if 명령문의 단축 형태로 쓰인다.
구문
condition
? truthyClause
: falsyClause
기존 if 명령문 예시
const array = [];
let text = '';
if (array.length === 0) {
text = 'an array is empty';
} else {
text = 'an array is not empty';
}
console.log(text); // output: an array is empty
삼항 연산자 사용 예시
const array = [];
let text = array.length === 0
? 'an array is empty'
: 'an array is not empty';
console.log(text); // output: an array is empty
/*
const array = [];
let text = '';
array.length === 0
? text = 'an array is empty'
: text = 'an array is not empty';
console.log(text); // output: an array is empty
*/
아래와 같이 삼항 연산자를 중첩으로 사용할 수 있다.
const age = 17;
const isStudent = true;
const message = age > 18
? 'You are allowed to drink.'
: isStudent
? 'Kid, go back to school.'
: 'Anyways, you are not allowed to drink.';
console.log(message); // output: Kid, go back to school.
중첩으로 삼항 연산자를 사용하면 기존 if 명령문에 비해 가독성이 떨어질 수 있다고 한다. 하지만 Nested Ternaries are Great 포스트에서도 볼 수 있듯 취향에 맞게 사용하면 될 듯하다.