Ternary operators in JavaScript are a shorthand way of writing conditional statements. They are called "ternary" because they involve three operands: a condition, an expression to be executed if the condition is true, and an expression to be executed if the condition is false. The syntax of a ternary operator is as follows:
Here, condition is any expression that can be evaluated as either true or false. If condition is true, then expression1 is executed; otherwise, expression2 is executed.
Let's take a look at some examples to illustrate how ternary operators work in JavaScript:
Example 1: Basic usage
In this example, we define a boolean variable isTrue with a value of true. We then use the ternary operator to assign the string 'Yes' to the result variable if isTrue is true. Since isTrue is true, the output of the console.log statement will be 'Yes'.
Example 2: Using expressions
In this example, we define a variable age with a value of 20. We use the ternary operator to assign the string 'You are an adult' to the result variable if age is greater than or equal to 18. Since age is 20, the output of the console.log statement will be 'You are an adult'.
Example 3: Nesting ternary operators
In this example, we define a variable num with a value of 10. We use a nested ternary operator to assign the string 'Positive' to the result variable if num is greater than 0, the string 'Negative' if num is less than 0, and the string 'Zero' if num is equal to 0. Since num is greater than 0, the output of the console.log statement will be 'Positive'.
Overall, ternary operators can be useful for writing more concise and readable code in JavaScript, especially for simple conditional statements. However, it is important to use them appropriately and avoid nesting them too deeply, as this can make the code more difficult to read and understand.
Thanks for reading and learning!