How Ternary Operator Work In JavaScript

A ternary is a conditional operator in JavaScript that allows us to concisely write a conditional statement. Ternaries use the syntax 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.

Here is an example of how a ternary works in JavaScript:

// 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.