Conditional (ternary) operator
Baseline Widely availableThis feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
>The conditional (ternary) operator is the only JavaScript operator that takes three operands:
a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.
This operator is frequently used as an alternative to an if...else statement.
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
jscondition ? exprIfTrue : exprIfFalse
Parameters
condition-
An expression with precedence 3 (logical OR or nullish coalescing) or above whose value is used as the condition. Besides
false, possible falsy values are:null,NaN,0,0n, the empty string (""), andundefined. exprIfTrue-
An expression with precedence 2 (assignment) or above, evaluated only if
conditionis truthy. exprIfFalse-
An expression with precedence 2 (assignment) or above, evaluated only if
conditionis falsy.
Return value
The value of exprIfTrue if condition is truthy, or the value of exprIfFalse otherwise.
Examples
>A basic example
jsconst age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Beer"
Handling null values
One common usage is to handle a value that may be 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
The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain:
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
This is equivalent to the following if...else chain.
function example() {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
}
Specifications
| Specification |
|---|
| ECMAScript® 2027 Language Specification > # sec-conditional-operator > |
Browser compatibility
See also
if...else- Nullish coalescing operator (
??) - Optional chaining (
?.) - Learn: Making decisions in your code — conditionals
- Expressions and operators guide
Help improve MDN
Was this page helpful to you? Yes No Learn how to contributeThis page was last modified on Nov 23, 2026 by MDN contributors.
View this page on GitHub • Report a problem with this content