조건 (삼항) 연산자

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

조건 (삼항) 연산자는 JavaScript에서 세 개의 피연산자를 받는 유일한 연산자입니다. 앞에서부터 조건문, 물음표(?), 조건문이 참(truthy)일 경우 실행할 표현식, 콜론(:), 조건문이 거짓(falsy)일 경우 실행할 표현식이 배치됩니다. 해당 연산자는 if...else문의 대체재로 빈번히 사용됩니다.

시도해보기

function getFee(isMember) {
  return isMember ? "$2.00" : "$10.00";
}

console.log(getFee(true));
// Expected output: "$2.00"

console.log(getFee(false));
// Expected output: "$10.00"

console.log(getFee(null));
// Expected output: "$10.00"

구문

js
condition ? exprIfTrue : exprIfFalse;

매개변수

condition

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

exprIfTrue

conditiontruthy한 값으로 평가될 경우 실행되는 표현식 (true와 같거나, true로 치환될 수 있는 값)

exprIfFalse

conditionfalsy한 값으로 평가될 경우 실행되는 표현식 (false와 같거나, false로 치환될 수 있는 값)

설명

false 이외의 falsy한 표현식에는 null, NaN, 0, 비어있는 문자열 (""), 그리고 undefined가 있습니다. condition이 이 중 하나일 경우 조건 연산자의 결괏값은 exprIfFalse 표현식을 실행한 결괏값입니다.

예제

간단한 예제

js
var age = 26;
var beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Beer"

null 값 처리하기

null일 수 있는 값을 처리할 때 흔히 사용됩니다:

js
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와 유사합니다.

js
function example() {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

위 코드는 아래의 연결된 if … else와 동등합니다.

js
function example() {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}

명세

Specification
ECMAScript® 2025 Language Specification
# sec-conditional-operator

브라우저 호환성

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
Conditional operator (c ? t : f)

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

같이 보기