JavaScript Ternary Operator
JavaScript Ternary Operator
When writing programs, we often need to make decisions. For example, we may want to display different messages depending on a condition. Normally, we use if...else
statements to handle this.
However, JavaScript provides a shorter and cleaner way to write these conditional statements using the ternary operator. The ternary operator is a shorthand way of writing conditional statements in JavaScript. Instead of writing multiple lines using if...else
, you can achieve the same result in a single line.
It is called a ternary operator because it takes three operands:
- A condition to evaluate.
- The result if the condition is true.
- The result if the condition is false.
Ternary Operator Syntax
The Ternary operator syntax are as follows:
condition ? expressionIfTrue : expressionIfFalse;
– condition
: The expression that will be evaluated.
– expressionIfTrue
: The result if the condition evaluates to true
.
– expressionIfFalse
: The result if the condition evaluates to false
.
The Ternary operator starts with conditional expression followed by ? operator. The expression after ? and before : will be executed if the condition is True. If the condition is false the expression after : will be executed.
Example Code
let age = 18; let message = (age >= 18) ? "You are an adult." : "You are a minor."; console.log(message);
In the above example:
– The condition is age >= 18
.
– If the condition is true, the message will be "You are an adult."
.
– If the condition is false, the message will be "You are a minor."
.
Since the value of age
is 18
, the output will be:
You are an adult.