By Hemanta Sundaray on 2022-03-16
We can simplify an if...else statement using a ternary operator.
Consider the following example:
let batteryLevel = 0.02
if (batteryLevel < 0.01) {
console.log("Activate battery saving mode.")
} else {
console.log("Do not activate battery saving mode.")
}
// Do not activate battery saving mode.
We can use a ternary operator to perform the same functionality:
let batteryLevel = 0.02
batteryLevel < 0.01
? console.log("Activate the battery saving mode.")
: console.log("Do not activate the battery saving mode.")
// Do not activate the battery saving mode.
In the example above:
Like if...else statements, ternary operators can be used for conditions which evaluate to true or false.