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.tsx35 chars2 lines
Here's an example:
index.tsx147 chars4 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.tsx155 chars4 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
.
gistlibby LogSnag