Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

3 Conditional Structures

6 Ternary Operator

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.

Example

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.