The JavaScript 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 a shortcut for the if
statement.
Example 1: Basic Conditional Rendering
// Check if a user is logged in
const isLoggedIn = true;
const greeting = isLoggedIn ? 'Welcome back!' : 'Please log in.';
console.log(greeting); // Outputs: 'Welcome back!'
Explanation
This example demonstrates the most common use case for the ternary operator. It checks the value of isLoggedIn
and assigns a different string to the greeting
variable based on whether the condition is true or false, making it a concise alternative to an if-else statement.
Example 2: Assigning a Default Value
// Assign a default value if one is not provided
let customColor;
const defaultColor = 'blue';
const selectedColor = customColor ? customColor : defaultColor;
console.log(selectedColor); // Outputs: 'blue'
Explanation
Here, the ternary operator checks if customColor
has a truthy value. Since customColor
is undefined
(a falsy value), the expression assigns the defaultColor
to selectedColor
.
Example 3: Null Check
// Check for null before accessing a property
const user = { name: 'John' };
const userName = user ? user.name : 'Guest';
console.log(userName); // Outputs: 'John'
Explanation
This code safely accesses the name
property of the user
object. The ternary operator first checks if the user
object is not null or undefined, preventing potential "Cannot read properties of null" errors.
Example 4: Function Call within a Ternary
// Call different functions based on a condition
const isAuthenticated = false;
const login = () => 'Logging in...';
const logout = () => 'Logging out...';
const action = isAuthenticated ? logout() : login();
console.log(action); // Outputs: 'Logging in...'
Explanation
The ternary operator can also execute functions. In this snippet, because isAuthenticated
is false, the login()
function is called and its return value is assigned to the action
variable.
Example 5: Multiple Ternary Operators (Chaining)
// Determine a student's grade based on their score
const score = 85;
const grade = score > 90 ? 'A' : score > 80 ? 'B' : 'C';
console.log(grade); // Outputs: 'B'
Explanation
This example chains ternary operators to create a more complex conditional logic similar to an if-else if-else statement. It checks the score
against multiple conditions sequentially to determine the correct grade
.
Example 6: Setting CSS Class Names Dynamically
// Set a CSS class based on component state
const isActive = true;
const className = `button ${isActive ? 'active' : 'inactive'}`;
console.log(className); // Outputs: 'button active'
Explanation
This demonstrates how the ternary operator can be used within a template literal to dynamically construct a string. It's a common pattern in web development for conditionally applying CSS classes.
Example 7: Ternary for Pluralization
// Pluralize a word based on a count
const itemCount = 1;
const itemText = `You have ${itemCount} item${itemCount !== 1 ? 's' : ''}.`;
console.log(itemText); // Outputs: 'You have 1 item.'
Explanation
This code snippet uses the ternary operator to handle pluralization. It checks if itemCount
is not equal to 1; if true, it adds an 's' to "item," otherwise, it adds an empty string.