31. The Ternary Operator
The ternary operator (? :) is a shorthand way to write simple if...else statements, often used for setting a variable based on a condition.
Syntax
condition ? value_if_true : value_if_false
Example 1: Basic Conditional Assignment
Imagine we want to set a status message based on a score:
javascript let score = 75;
// Traditional if/else: // let status; // if (score >= 60) { // status = 'Pass'; // } else { // status = 'Fail'; // }
// Ternary equivalent (one line): let status = score >= 60 ? 'Pass' : 'Fail';
console.log(status); // Output: Pass
Example 2: Nested Ternary (Caution!)
While possible, nesting ternaries makes code harder to read and is often discouraged.
javascript let userType = 'admin';
let message = (userType === 'admin') ? 'Welcome, Administrator!' : (userType === 'guest') ? 'Please log in.' : 'Hello User.';
console.log(message); // Welcome, Administrator!