JavaScript - Conditional Operators
JavaScript - Conditional Operators
JavaScript Conditional Operators
Theconditionaloperator in JavaScript first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator is also known as theternaryoperator.
The JavaScript conditional (ternary) operator is only operator that takes three operands a condition followed by a question mark (?), then the first expression to be executed if the condition istruthyfollowed by a colon (:), and finally the second expression to be executed if the condition isfalsy.
There are sixfalsyvalues in JavaScript. These are β 0 (zero), false, empty string (β or ""), null, undefined, and NaN. All other values are treated astruthyin JavaScript.
Syntax
Following is the syntax of conditional (ternary) operator in JavaScript β
var variable = condition ? exp1 : exp2;Parameters
Here, we have explained the parameters in the above statement.
- conditionβ It is a conditional statement.
- exp1β If the conditional statement evaluates truthy, control flow executes the exp1 expression.
- exp2β If the conditional statement evaluates falsy, control flow executes the exp2 expression.
If the value of theconditionis any falsy value, the result of the expression will be the value ofexp2; otherwise, it will be the value ofexp1.
Example
In the example below, we compare the value of the num1 and num2 variables in the conditional statement. Here, the conditional statement evaluates true, so the result variable contains the value of the first expression.
It will produce the following result β
num1 is greater than num2Example
In the example below, we assign the value to the object property according to the conditional statements result.
Now, imagine what if you need to write the if-else statement to assign value to each property conditionally. The code will become complex, but with the ternary operator, you can easily do it with a single line of code.
It will produce the following result β
John is adult and lives in New YorkExample
This example demonstrates that you can also use the expression instead of values. According to the conditional statement, control flow evaluates the first or second expression and assigns the resultant value to the βresultβ variable.
It will produce the following result β
The result is: -10In short, you can use the ternary or conditional operator to shorten the code, which uses the if-else statement.
Handling null values
We can use the JavaScript conational operator to handle null value to set a default value if the user passes a null value.
Example
Try the following example β
It will produce the following result β
Hello, John
Hello, stranger