삼항 조건 연산자
시도해보기
구문
condition ? exprIfTrue : exprIfFalse
매개변수
설명
false
외에도 null
,NaN
, 0
, 비어있는 문자 값 (""
), 그리고 undefined
으로 조건문에 false 값으로 사용 가능 합니다. 이 값들이 조건문으로 사용된다면 exprIfFalse
이 결과로 나오게 됩니다.
예제
간단한 예제
var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // "Beer"
null 값 처리하기
이와같이 null
값을 처리할 때에도 일반적으로 사용됩니다.:
let greeting = person => {
let name = person ? person.name : `stranger`
return `Howdy, ${name}`
}
console.log(greeting({name: `Alice`})); // "Howdy, Alice"
console.log(greeting(null)); // "Howdy, stranger"
연속된 조건문 처리하기
삼항 연산자는 if … else if … else if … else
와 같은 "연속된 조건"을 사용할 수 있습니다.
function example(…) {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
// 위의 코드는 아래의 코드와 동일합니다.
function example(…) {
if (condition1) { return value1; }
else if (condition2) { return value2; }
else if (condition3) { return value3; }
else { return value4; }
}
명세
Specification |
---|
ECMAScript Language Specification # sec-conditional-operator |
브라우저 호환성
BCD tables only load in the browser