Developers prefer to write concise and compact code in various scenarios for better understanding and enhancing code readability. For instance, when a conditional statement is simple and short it is best practice to write it in one line to make it easily understandable. While, for more complex if statements or for those with multiple branches, it is generally recommended to use the multi-line format instead of one line.
This tutorial will describe the way to write a one line ‘if’ statement.
How to Create If Statement One-Liners in JavaScript?
To create a one-liner if statement, use the “ternary operator”. It contains three operands, “true expression”, “false expression”, and a “condition” with “?” and “:” signs. These signs indicate and separate the operands.
Syntax
The following syntax is utilized for the one-liner if statement:
The “true expression” will execute when the “condition” is true, else the “false expression” will be executed.
Example
Create a variable “grade” and store string “A”:
Now, use the ternary operator and check whether the variable “grade” stores “A”. If “yes” then print “Superb” otherwise, print “Best”:
In the given output, the true expression will be executed because the condition is “true”:
You can also create multiple if statements in one line using the ternary operator. Here, the variable “grade” stores “D”:
Now, check whether the “grade” stores “A”. if yes, then print “Superb”, if “grade” stores “B” print “Best”, if it stores “C” print “Good”, else print “Fair”:
Output
Here, in the above output, none of the conditions is true, so the else statement is executed:
Conclusion
For creating a one-liner if statement, use the “ternary operator”. It contains three operands, “true expression”, “false expression”, and a “condition” with “?” and “:” signs. These signs indicate and separate the operands. The ternary operator is also known as a shortcut for if-else statements. In this tutorial, we described the way to create an ‘if’ statement in one line.