The `?:` ternary operator, also known as the conditional operator, is a concise way to write an inline conditional expression in JavaScript. It provides a shorter syntax for expressing simple conditional statements.
The general syntax of the ternary operator is:
condition ? expressionIfTrue : expressionIfFalse;
Here, `condition` is the test condition that evaluates to either `true` or `false`. If the condition is `true`, the expression before the colon (`:`) is executed; otherwise, the expression after the colon is executed.
Here's a simple example:
let age = 20;let isAdult = age >= 18 ? "Yes" : "No";console.log(isAdult); // Output: Yes
In this example, the condition `age >= 18` is evaluated. If it's `true`, the value `"Yes"` is assigned to the variable `isAdult`; otherwise, the value `"No"` is assigned.
The ternary operator is often used for assigning values based on a condition or for producing conditional results in a concise manner. It's particularly useful when you need to assign a value to a variable based on a simple condition without writing a complete `if-else` statement.
Here's another example that involves using the ternary operator in a function:
function getDiscount(isMember) {return isMember ? 0.2 : 0;}let memberDiscount = getDiscount(true);console.log("Discount:", memberDiscount); // Output: Discount: 0.2let nonMemberDiscount = getDiscount(false);console.log("Discount:", nonMemberDiscount); // Output: Discount: 0
In this example, the `getDiscount` function uses the ternary operator to determine the discount percentage based on whether a customer is a member (`isMember` is `true`) or not (`isMember` is `false`). The function returns `0.2` for members and `0` for non-members.
Social Plugin