As the name suggests, the ternary operator takes three arguments, one of which is a boolean or a condition that resolves in a boolean expression. The other two are the expressions that would execute once the boolean is true or false.
Here is the syntax of the ternary operator.
The condition before the question mark is our boolean expression which, when true would execute statement1 as output. Otherwise, it would run stataement2 if false. Both statements are separated by a colon sign.
As the ternary operator is similar to the if-else statement, here is the equivalent if-else block for evaluating the condition.
The ternary operator works the same way as the if-else statement. When the condition is considered correct, statement1 executes otherwise statement2 executes. Here is an example that uses the ternary operator.
let judge = x?"it is not falsy":"it is falsy";
}falsy(0); //output:- it is falsy
Here, I made a little function that checks the falsy values and gives output on whether the value is falsy or not. If the value passed is a falsy value, the output would be stored in the judge variable as “it is falsy” otherwise it would output as “it is not falsy”.
This small example is enough to show how the ternary operator executes a conditional operation and can be used in a function.
0, null, undefined, NaN, false, “”(empty strings)
Real Life Usages:
Here is a little example of a function that I made for one of my personal React projects that use Ternary Operator.
I know it doesn’t look too clean😅 but this is an example of using ternary operators in React project. Here, I made a ternary operator that checks whether a title is available or not. First, it checks whether the title is present or not, if it is present, then it checks the length of the title. If the title is over 40 characters long, then it is sliced to 40 characters.
If there is no title present, then a string of “No title is available” is sent as output.
This is also an example of chaining the ternary operators as we do in if…else…if ladder.
This is what it looks in if…else…if
return "No title is available"
This was everything there is to know about Ternary operators. This article was a part of the series in which I post about topics that are important to know before learning ReactJS. I hope you enjoyed the article and found it helpful.
If you too are interested in learning ReactJS then here are all the concepts important. I recommend doing these, before learning React.
Have a great day ahead😉.