JS Ternary
JS Ternary
JS Ternary operator is a shorthand version of an if-else statement. It is often used to assign a value to a variable based on a condition.
Syntax:
condition ? trueValue : falseValue;
The condition is the expression that needs to be evaluated. If the condition is true, then the trueValue is returned, else the falseValue is returned.
Let's say you want to assign a value to a variable based on whether a number is even or odd. You can use the ternary operator to achieve this:
let num = 10;
let result = num % 2 === 0 ? "even" : "odd";
console.log(result); // Output: even
In this example, the condition is num % 2 === 0
, which returns true when num
is even. If the condition is true, then the value "even" is assigned to result
, else the value "odd" is assigned to result
.
You can also nest ternary operators to make more complex decisions:
let age = 18;
let result = age < 18 ? "Underage" : age < 25 ? "Young Adult" : "Adult";
console.log(result); // Output: Young Adult
In this example, if the age
is less than 18, then the value "Underage" is assigned to result
. If it is not, then the next condition age < 25
is evaluated. If it is true, then the value "Young Adult" is assigned to result
. If it is false, then the value "Adult" is assigned to result
.
The ternary operator is a concise and powerful way to make decisions in JavaScript.