Ternary Operator with Google Apps Script
The ternary operator allows for writing a condition on a single line like this:
condition ? value_if_true : value_if_false
Usage Example
In this example, the variable category gets a value based on a condition:
let category;
if (age >= 18) {
category = 'Adult';
} else {
category = 'Child';
}
Using the ternary operator, all these lines can be reduced to one:
const category = age >= 18 ? 'Adult' : 'Child';
Example with true and false
In this similar example, the variable adult gets the value true or false based on the same condition:
let adult;
if (age >= 18) {
adult = true;
} else {
adult = false;
}
The ternary operator is also usable in this case:
const adult = age >= 18 ? true : false;
But to only return true or false, the result of the condition is sufficient:
const adult = age >= 18;