Ternary Operation in Javascript

A ternary operation is a concise way of writing an if-else statement. It is also known as the conditional operator.

Syntax as follows

condition ? expression_if_true : expression_if_false;

Explanation

Condition: This is the expression that is evaluated. If it is truthy, the expression before the colon (:) is executed; otherwise, the expression after the colon is executed.

  • expression_if_true: The value or expression to be returned if the condition is true.
  • expression_if_false: The value or expression to be returned if the condition is false.

Example

var age = 20;
var message = (age >= 18) ? 'You are an adult' : 'You are a minor';

console.log(message);

Output

if age is greater than or equal to 18, the message variable will be assigned the value 'You are an adult'; otherwise, it will be assigned the value 'You are a minor'. The value for the result will be logged to the console.