Learn Programming Fundamentals
1 Programming Fundamentals
2 Variables Data Types
4 Strings
5 Arrays
6 Objects
8 Functions
The ternary operator is a concise way to write simple if-else statements in a single line of code. It is ideal for making decisions based on conditions within your program. Here's how it works:
condition ? value1 : value2
If the condition is true, value1
is returned; otherwise, value2
is returned. It's a compact alternative to traditional if-else statements.
let age = 20; let status = (age >= 18) ? "Adult" : "Minor"; console.log(status); // Output: "Adult"
In this example, if age
is greater than or equal to 18, status
is assigned the value "Adult"; otherwise, it's assigned "Minor".
The ternary operator is handy for writing concise conditional expressions, particularly when assigning values based on a single condition.