Learn the basics of the JavaScript Ternary Operator
The ternary operator is the only operator in JavaScript that works with 3 operands, and it’s a short way to express conditionals.
This is how it looks:
<condition> ? <expression> : <expression>
The condition <condition>
is evaluated as a boolean, and upon the result, the operator runs the first expression (if the condition is true) or the second.
This operator is real useful to handle conditions that has if
and else
statements
This is an example: we define a function getFee
to calculate a Fee based on the user type:
function getFee(isMember) {
if (isMember) {
return '$2.00';
}
return '$10.00';
}
console.log(getFee(true));
// expected output: '$2.00'
Or we can simplified it in the next way using the ternay operator:
function getFee(isMember) {
return isMember ? '$2.00' : '$10.00';
}
console.log(getFee(true));
// expected output: '$2.00'