Javascript conditional operator or ternary operator
In this article, we will learn about the javascript conditional operator or you can say, ternary operator.
Basically, this operator is worked as an if-else condition, but it can make your code much cleaner. Let’s look at the basic definition of the conditional operator.
What is conditional(ternary) operator in javascript?
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?
), then an expression to execute if the condition is truthy followed by a colon (:
), and finally, the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.
The above definition is taken from the Mozilla firefox developer website.
Syntax of conditional (ternary) operator
variablename = (condition) ? value1:value2
Let’s Look at the below example, that is what all we have to do when we are using the If else statement in our code.
var age = 19;
var canDrive;
if (age > 16) {
canDrive = 'yes';
} else {
canDrive = 'no';
}
Now we will see the same above example as the conditional operator or ternary operator.
var age = 19;
var canDrive = age > 16 ? 'yes' : 'no';
The conditional operator (ternary) makes our code much cleaner, and even it reduced the number of code lines.