The ternary operator allows you to make a choice based on a condition and return a corresponding value.
The ternary operator is an operator that can replace an if-else conditional statement. This helps to shorten the source code and make the code easier to read.
The syntax of the ternary operator is as follows:
<biến kết quả> = <điều kiện> ? <giá trị nếu đúng> : <giá trị nếu sai>;
Where:
Let's see some examples of using the ternary operator in programming languages.
Example 1: Check even/odd number
let number = 7
let result = number % 2 == 0 ? "Chẵn" : "Lẻ"
console.log(result)
In this example, we use the ternary operator to check if the number is even or odd. If the number is divisible by 2, we assign the value "Even" to the result variable, otherwise we assign the value "Odd".
Example 2: Compare two numbers
let a = 5;
let b = 10;
let max = (a > b) ? a : b;
console.log(max); // Output: 10
In this example, we use the ternary operator to compare two numbers a and b. If a is greater than b, we assign the value of a to the variable max, otherwise we assign the value of b.