Ternary Operators
Ternary operators is also known as the conditional operator. It is a shorthand way of writing an if...else
statement in a single line. The ternary operator takes three operands: a condition followed by a question mark (?
), an expression to execute if the condition is true, followed by a colon (:
), and an expression to execute, if the condition is false.
Here is the syntax of the ternary operator:
condition ? expression1 : expression2
If the condition is true, expression1
is executed; otherwise, expression2
is executed.
Example
Here is an example of using the ternary operator to check if a number is even or odd:
let num = 5;
let result = num % 2 === 0 ? "Even" : "Odd";
console.log(result); // Output: Odd
In the example above, the ternary operator checks if the remainder of num
divided by 2
is equal to 0
. If the condition is true, the result is set to "Even"
; otherwise, it is set to "Odd"
.
Nested Ternary Operators
You can also nest ternary operators to create more complex conditions. However, nesting ternary operators can make the code less readable and harder to maintain. It is recommended to use nested ternary operators sparingly.
Here is an example of using nested ternary operators to check if a number is positive, negative, or zero:
let num = 5;
let result = num > 0 ? "Positive" : num < 0 ? "Negative" : "Zero";
console.log(result); // Output: Positive
In the example above, the first ternary operator checks if num
is greater than 0
. If the condition is true, the result is set to "Positive"
. If the condition is false, the second ternary operator checks if num
is less than 0
. If the condition is true, the result is set to "Negative"
. If both conditions are false, the result is set to "Zero"
.
That's it! You now know how to use the ternary operator in JavaScript to create conditional expressions in a concise way. Happy coding! 🚀
In the next section, we will learn about logical operators in JavaScript. Let's keep going! 🚀
Made with ❤️ by Fasakin Henry