First, we must look at what a ternary operator is:
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 an alternative to an if...else statement.
Source: MDN
Essentially, it is a way to write an If/Else statement in fewer lines of code. What is the syntax you may be asking yourself.
condition ? ifTrue : thenFalse
What does this mean? Simply put you write a condition first. Let's say you want to see if someone is legal drinking age or if they are underage. First you'd establish the person's age then write a ternary expression to determine if this person is legal to drink (ifTrue) or underage (thenFalse).
If the statement is true, it will look like this:
If it is false, the final result will be this:
Top comments (0)