조건(삼항) 연산자

조건(삼항) 연산자 (condition ? exprIfTrue : exprIfFalse)

조건(삼항) 연산자는 세 개의 피연산자를 취하는 유일한 JavaScript 연산자입니다. 조건 뒤에 물음표(?)가 오고, 조건이 참이면 실행할 표현식이 옵니다. 그 뒤 콜론(:)이 오고, 마지막으로 조건이 거짓이면 실행할 표현식이 옵니다. 이 연산자는 if...else 문의 대안으로 자주 사용됩니다.

호환성: Baseline — 널리 사용 가능(Widely available). 이 기능은 잘 확립되어 있으며 많은 기기와 브라우저 버전에서 작동합니다. 2015년 7월부터 브라우저에서 사용할 수 있습니다.

출처: Conditional (ternary) operator

본문

Try it

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"

구문 (Syntax)

condition ? exprIfTrue : exprIfFalse

매개변수 (Parameters)

  • condition: 값이 조건으로 사용되는 표현식입니다.
  • exprIfTrue: 조건이 참(truthy) 값(즉 true와 같거나 true로 변환될 수 있는 값)으로 평가되면 실행되는 표현식입니다.
  • exprIfFalse: 조건이 거짓(falsy, 즉 false로 변환될 수 있는 값)이면 실행되는 표현식입니다.

설명 (Description)

false 외에도 가능한 거짓 표현식은 다음과 같습니다: null, NaN, 0, 빈 문자열(""), undefined. 조건이 이 중 하나이면 조건부 표현식의 결과는 exprIfFalse를 실행한 결과가 됩니다.

예제 (Examples)

기본 예제 (A basic example)

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

null 값 다루기 (Handling null values)

흔한 사용법 중 하나는 null일 수 있는 값을 다루는 것입니다.

const greeting = (person) => {
  const name = person ? person.name : "stranger";
  return `Howdy, ${name}`;
};

console.log(greeting({ name: "Alice" })); // "Howdy, Alice"
console.log(greeting(null)); // "Howdy, stranger"

조건 체인 (Conditional chains)

삼항 연산자는 오른쪽 결합(right-associative)입니다. 이는 다음 방식으로 "연결"될 수 있음을 뜻하며, if … else if … else if … else 체인과 유사합니다.

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

이는 다음 if...else 체인과 동일합니다.

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

명세 (Specifications)

ECMAScript® 2027 언어 명세 — sec-conditional-operator

더 알아보기