The ternary operator evaluates a condition then returns one of two responses depending on whether the condition evaluates as true or false.
The structure of the ternary operator is as follows:
condition ? response if true : response if false
The ternary operator can be used to assign a value to a variable depending on a condition.
let skyColor = (isDaytime) ? 'blue' : 'black' // skyColor set to blue if isDaytime is true, or black if false
The example above can be written as an if-statement:
let skyColor
if (isDaytime) {
skyColor = 'blue'
} else {
skyColor = 'black'
}
This example shows how simple if-statements can be replaced by one line of code using a ternary operator.
Another interesting example is a toggle:
let toggle = (toggle) ? false : true
In this example, the variable toggle uses a ternary operator to check its own value, then assigns the opposite. The result is therefore to literally toggle the value from true to false or vice-versa. A potential use for this idea would be for a button which toggles the visibility of a mobile menu.