조건부 삼항 연산자는 JavaScript에서 세 개의 피연산자를 취할 수 있는 유일한 연산자입니다. 보통 if
명령문의 단축 형태로 쓰입니다.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
구문
condition ? exprIfTrue : exprIfFalse
매개변수
condition
- An expression whose value is used as a condition.
exprIfTrue
- An expression which is evaluated if the
condition
evaluates to a truthy value (one which equals or can be converted totrue
). exprIfFalse
- An expression which is executed if the
condition
is falsy (that is, has a value which can be converted tofalse
).
설명
condition
이 true
이면, 연산자는 expr1
의 값을 반환하며, 반대의 경우 expr2
를 반환한다.
예제
여러분이 술을 마실수 있는지 확인할 수 있는 간단한 예제가 여기 있습니다.
var age = 29;
var canDrinkAlcohol = (age > 19) ? "True, over 19" : "False, under 19";
console.log(canDrinkAlcohol); // "True, over 19"
isMember 변수의 값을 기준으로 다른 메시지를 보여주고자 한다면, 다음과 같이 표현할 수 있다.
"The fee is " + (isMember ? "$2.00" : "$10.00")
또한 다음과 같이 삼항(ternary)의 결과에 따라 변수를 할당할 수도 있다.
var elvisLives = Math.PI > 4 ? "Yep" : "Nope";
다음의 예제처럼, 다중 삼항(ternary) 평가도 가능하다(주의: 조건 연산은 우측부터 그룹핑 됩니다.)
var firstCheck = false,
secondCheck = false,
access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted";
console.log( access ); // logs "Access granted"
또한 다중 조건 IF 문과 같은 방식으로 여러개의 조건을 사용할 수도 있습니다.
var condition1 = true,
condition2 = false,
access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false");
console.log(access); // logs "true false"
참고 : 괄호는 필수는 아니며 기능에 영향을주지 않습니다. 결과가 어떻게 처리되는지 시각화하는 데 도움이됩니다.
삼항(ternary) 평가는 다른 연산을 하기 위해 쓸 수도 있습니다.
var stop = false, age = 16;
age > 18 ? location.assign("continue.html") : stop = true;
하나의 케이스 당 둘 이상의 단일 작업을 수행하려면 쉼표로 구분하고 괄호로 묶으세요.
var stop = false, age = 23;
age > 18 ? (
alert("OK, you can go."),
location.assign("continue.html")
) : (
stop = true,
alert("Sorry, you are much too young!")
);
또한, 값을 할당하는 동안 하나 이상의 연산도 가능합니다. 이 경우에, 괄호 안의 값중 마지막 쉼표 (,) 다음의 값이 최종 할당 값이 됩니다.
var age = 16;
var url = age > 18 ? (
alert("OK, you can go."),
// alert returns "undefined", but it will be ignored because
// isn't the last comma-separated value of the parenthesis
"continue.html" // the value to be assigned if age > 18
) : (
alert("You are much too young!"),
alert("Sorry :-("),
// etc. etc.
"stop.html" // the value to be assigned if !(age > 18)
);
location.assign(url); // "stop.html"
삼항 연산자로 반환하기
삼항 연산자는 if / else
문을 사용하는 함수를 반환하는 데 적합합니다.
var func1 = function( .. ) {
if (condition1) { return value1 }
else { return value2 }
}
var func2 = function( .. ) {
return condition1 ? value1 : value2
}
다음과 같이 법적으로 술을 마실수 있는지 여부를 반환하는 함수를 만들수 있습니다.
function canDrinkAlcohol(age) {
return (age > 21) ? "True, over 21" : "False, under 21";
}
var output = canDrinkAlcohol(26);
console.log(output); // "True, over 21"
if / else
문을 대체하는 삼항연산자가 return
을 여러 번 사용하고 if 블록 내부에서 한줄만 나올때 return
을 대체 할 수 있는 좋은 방법이됩니다.
삼항연산자를 여러 행으로 나누고 그 앞에 공백을 사용하면 긴 if / else
문을 매우 깔끔하게 만들 수 있습니다. 이것은 동일한 로직을 표현하지만 코드를 읽기 쉽게 만들어 줍니다.
var func1 = function( .. ) {
if (condition1) { return value1 }
else if (condition2) { return value2 }
else if (condition3) { return value3 }
else { return value4 }
}
var func2 = function( .. ) {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4
}
명세
Specification | Status | Comment |
---|---|---|
ECMAScript (ECMA-262) The definition of 'Conditional Operator' in that specification. |
Living Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Conditional Operator' in that specification. |
Standard | |
ECMAScript 5.1 (ECMA-262) The definition of 'The conditional operator' in that specification. |
Standard | |
ECMAScript 1st Edition (ECMA-262) The definition of 'The conditional operator' in that specification. |
Standard | Initial definition. Implemented in JavaScript 1.0. |
브라우저 호환성
BCD tables only load in the browser