How to Write Cleaner Code with Ternary Operators.
How to simplify Conditional Statements in JavaScript
The ternary operator is a feature that was introduced in ES6 to simplify condional if else statements. The syntax looks like this
The condition is the determining factor of what will be evaluated. After the ?
(question mark), the expression that evaluates to true will be executed, while the expression after the :
(colon) is executed if the condition evaluates to false. For example, in the code condition ? expression1 : expression2
, if the condition is true, expression1
will be executed; otherwise, expression2
will be executed.
A traditional if else statement looks like this.
The if block checks if the condition is true, and if true, it will run expression 1. If the condition is false, the else block will run expression 2. This allows you to handle different outcomes based on a single condition.
The else block runs the code that doesn't satisfy the first condition, providing a fallback option. However, using a ternary operator, you can achieve the same result in a more concise manner since it's only a single line, which in turn makes your code cleaner and easier to read.
Letβs look at an example,
We have a function called getMedal()
that takes position as an argument. If the position is between 1 and 3, we give the user a medal; otherwise, we give no medal.
With a ternary operator, it will look like this:
Chaining Ternary Operator
Suppose we need to specify the medal someone will receive based on their position. For example, in position 1, the medal is "gold"; in position 2, it's "silver"; and in position 3, it's "bronze". We can use the ternary operator to chain the conditions like this:
Conclusion
The ternary operator is great for simplifying multiple statements, but its overuse, especially for complex conditions, can make code harder to read; therefore, it is ideal for simple statements.