condition ? value1 : value2, where
condition is a boolean expression,
value1 is the value to be returned if the
condition is true, and
value2 is the value to be returned if the
condition is false.
// Define a variable and assign a value var score = 80; // Use a ternary to check if the score is passing or failing var result = score >= 60 ? 'passing' : 'failing'; // Log the result to the console console.log(result); // 'passing'
In this example, we are defining a variable and assigning it a value. We are then using a ternary to check if the value of the variable is greater than or equal to 60. If the condition is true, the
'passing' value is returned. If the condition is false, the
'failing' value is returned.
The result of the ternary is assigned to a variable and is logged to the console. This shows how we can use a ternary to concisely handle a conditional statement and return a value based on the result of the condition.
I hope you find this useful. Please comment if you have any questions.