Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Conditional operator (?:)

The conditional operator `?:` selects one of two values based on a condition. It is an expression: it evaluates the condition and then only the selected branch, whose value becomes the result.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

condition ? expressionIfTrue : expressionIfFalse

The conditional operator has the form condition ? expressionIfTrue : expressionIfFalse and takes three operands, so it is also called the ternary operator. The ? starts the branch for a true condition, and : separates it from the branch for a false condition. Both branches are required.

First, condition is evaluated and its value is interpreted logically using ToBoolean; it need not have type boolean. For example, 0 and "" are falsy, whereas "0" is truthy. Only the selected branch is then evaluated. Its value is the result, without automatic conversion to boolean.

Unlike an if...else statement, ?: is an expression, so it can appear on the right side of an assignment or after return. Use it for a short choice of values; if...else can be clearer for more elaborate actions.

The operator is right-associative: a ? b : c ? d : e means a ? b : (c ? d : e). Parentheses help clarify nesting and combinations with other operators. In the example, "pass" is selected, so fallback() is not called.

Examples

let calls = 0;
function fallback() {
  calls += 1;
  return "unknown";
}
const score = 80;
const result = score >= 60 ? "pass" : fallback();
console.log(result);
console.log(calls);

Result

pass
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources