| by Arround The Web | No comments

How to Create If Statement One-Liners Using JavaScript

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:

condition ? true_expression : false_expression

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”:

let grade = "A";

Now, use the ternary operator and check whether the variable “grade” stores “A”. If “yes” then print “Superb” otherwise, print “Best”:

grade == "A" ? "Superb" : "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”:

let grade = "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”:

grade == "A" ? "Superb": grade == "B" ? "Best": grade == "C" ? "Good": "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.

Share Button

Source: linuxhint.com

Leave a Reply