ejemplo de operador ternario in javascript

The ternary operator is a shorthand way to write an if...else statement. It takes three operands - a condition, a result for the true case, and a result for the false case.

index.tsx
condition ? true_case : false_case
35 chars
2 lines

Here's an example:

index.tsx
const x = 10;
const result = x > 5 ? 'x is greater than 5' : 'x is less than or equal to 5';
console.log(result); // Output: 'x is greater than 5'
147 chars
4 lines

In the above example, the condition is x > 5. If it's true, the value 'x is greater than 5' is assigned to result. If it's false, the value 'x is less than or equal to 5' is assigned to result. The value of result is then logged to the console.

The ternary operator can also be nested:

index.tsx
const num = 7;
const result = num > 10 ? 'greater than' : num < 5 ? 'less than 5' : 'between 5 and 10';
console.log(result); // Output: 'between 5 and 10'
155 chars
4 lines

In this example, the first condition (num > 10) is false, so we move on to the next condition (num < 5). This is also false, so we move on to the final condition, which is true. The value 'between 5 and 10' is assigned to result.

related categories

gistlibby LogSnag