The ternary operator is a streamlined way of handling conditional expressions, similar to the if / else statement.
Syntax
JavaScript
x
condition ? <expression if true> : <expression if false>
Using if/else
Here, we’re checking the authenticated
condition. If it is true, renderApp()
is called. If it is false, renderLogin()
is called.
JavaScript
// Before:
if (authenticated) {
renderApp();
} else {
renderLogin();
}
Using Ternary
In this example, the same condition is checked. If authenticated
is true, renderApp()
is executed. If it is false, renderLogin()
is executed. The ternary operator condenses this into a single line, making the code more readable.
The ternary operator simplifies conditional logic, making it more concise and often easier to read compared to traditional if/else statements. This is especially useful in React for rendering different components or elements based on a condition.
JavaScript
// With Ternary Operator
authenticated ? renderApp() : renderLogin();