Skip to main content

Conditional Operator in JavaScript – What Is a Ternary Operator?

A conditional operator is an alternate (shortcut) way of writing an if...else statement.

note
  • Conditional operators are sometimes called the ternary or question mark operators.
  • A conditional operator is the only JavaScript operator that accepts three operands. This is why it is called a ternary operator.

Syntax of a Ternary Operator in JavaScript

(condition)
? code to run if condition is true
: code to run if condition is false;

Example of a Ternary Operator in JavaScript

new Date().getHours() < 21
? console.log("Today is special!")
: console.log("Last minutes embody great opportunities!");

Try Editing It

The snippet above instructs the computer to log "Today is special!" on the browser's console if the time is less than 21:00. Else, the system should log out "Last minutes embody great opportunities!".

Example of a Ternary Operator in a JavaScript Function

const age = 19;

function checkIfQualified() {
return age > 35 ? "Qualified" : "Not Qualified!";
}

console.log(checkIfQualified());

Try Editing It

The snippet above instructs the computer to log "Qualified" on the browser's console if age is greater than 35. Else, the system should log out "Not Qualified!".

Keep in mind that the if...else equivalence of the ternary operator above is like so:

const age = 19;

function checkIfQualified() {
if (age > 35) {
return "Qualified";
} else {
return "Not Qualified!";
}
}

console.log(checkIfQualified());

Try Editing It

Overview

This article discussed the JavaScript conditional operator and used examples to illustrate how to define and use it.

Buy me a coffee