Conditional Operator in JavaScript – What Is a Ternary Operator?
A conditional operator is an alternate (shortcut) way of writing an if...else
statement.
Syntax of a Ternary Operator in JavaScript
Section titled “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
Section titled “Example of a Ternary Operator in JavaScript”new Date().getHours() < 21 ? console.log("Today is special!") : console.log("Last minutes embody great opportunities!");
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
Section titled “Example of a Ternary Operator in a JavaScript Function”const age = 19;
function checkIfQualified() { return age > 35 ? "Qualified" : "Not Qualified!";}
console.log(checkIfQualified());
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());