JS++ | Conditional Statements

Conditional statements of various kinds play a central role in JS++. In this tutorial, we will look at the basic syntax and some common uses of such statements, and we will also introduce two kinds of expressions that are often used in conditionals: comparison operators and logical operators.

Note: JS++ conditionals, comparison operators, and logical operators work in a similar way to their counterparts in languages such as JavaScript, Java, C++, and C#.

Let’s start by making a new folder – name it “Conditionals”. Then make a new file and name it “Conditionals.jspp”. Write in the following code:

external $;

string colorString;
bool likesRed = true;
if (likesRed) {
    colorString = "red";
}

$("#content").text(colorString);
$("#content").css("color", colorString);

Save Conditionals.jspp to your Conditionals folder. Then create a second file named “Conditionals.html” and write in the following:

<!DOCTYPE html>
<title>Conditionals program</title>
<body>

<p id="content"></p>

<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="Conditionals.jspp.js"></script>

</body>
</html>

Save Conditionals.html to your Conditionals folder. Compile Conditionals.jspp and then open Conditionals.html in a browser. If everything has worked, your document should display “red” in a red font.



“if”, “else”, and “else if”

Conditionals.jspp shows the syntax of a simple if statement: the keyword if itself, followed by a pair of parentheses holding a condition to check, followed by a block of code in curly braces which executes if and only if the condition is true.

Simple If Diagram

Note: the curly braces around the code block are optional if the block only contains one statement. For consistency and readability, however, it is advisable always to use curly braces.

Although if statements are often used on their own, they are also commonly used together with else statements. Let’s add an else statement to Conditionals.jspp:

external $;
    
string colorString;
bool likesRed = true;

if (likesRed) {
    colorString = "red";
}
else {
    colorString = "blue";
}
    
$("#content").text(colorString);    
$("#content").css("color", colorString);

Compile this code and then open Conditionals.html in a browser. The result is the same: the document still displays “red” in a red font. The reason is that the code in an else block only executes if the condition in the associated if statement is false. To get the code in your else block to execute, change the value of likesRed to false: Conditionals.html will then display “blue” in a blue font.



Notice that the else statement doesn’t specify a condition of its own; the only condition that is checked in Conditionals.jspp is likesRed. We simply have one block of code which executes if that condition is true, and another block which executes if it is false.

If Else Diagram

In some cases, however, we want the execution of our code to depend on more than one condition. This is where else if statements can prove useful. An else if statement supplies a condition of its own and an associated code block. The code block executes if the condition is true and all previous conditions (i.e. those associated with earlier if and else if statements) are false. Let’s revise Conditionals.jspp again to show the use of an else if statement:

external $;

string colorString;
bool likesRed = false;
bool likesBlue = true;

if (likesRed) {
    colorString = "red";
}
else if (likesBlue) {
    colorString = "blue";
}
else {
    colorString = "green";
}

$("#content").text(colorString);
$("#content").css("color", colorString);

Here the code in the else if block will execute, since its likesBlue condition is true whereas the likesRed condition specified by the earlier if statement is false. If we change the value of likesBlue to false, however, the code in the else if block will not execute, but the code in the else block will. Play around with the values of likesRed and likesBlue for yourself to see what effect they have on the conditional’s execution.

Comparison operators

Often when we use conditionals, it is because we want the execution of our code to depend on the result of a comparison of some kind. For example, suppose we want to check whether the value of a tempInCelsius variable is equal to 0, and have some code execute if it is. We would write:

if (tempInCelsius == 0) {
    // Code to be executed goes here
}

This conditional uses the equality operator “==”. An equality comparison returns true if the compared values are equal and false otherwise.

Note: the equality operator “==” is not the same as the assignment operator “=” . Take care with this distinction! If you accidentally use “=” in place of “==”, you will introduce bugs into your code which may be hard to spot.

JS++ contains various comparison operators in addition to “==”. To extend the temperature checking example, suppose we wanted to check not the exact value of tempInCelsius but rather what range it falls in. Our code might look like this:

if (tempInCelsius > 30) {
    // Code to execute if temperature is over 30
}
else if (tempInCelsius >= 15) {
    // Code to execute if temperature is between 15 and 30
}
else {
    // Code to execute if temperature is 14 or below
}

This example uses the greater than operator “>”, which returns true if the left operand is greater than the right operand, and the greater than or equal to operator “>=”, which returns true if the left operand is greater than or equal to the right operand. You can see the full range of comparison operators here:

Comparison operators in JS++



Logical operators

Sometimes we want code to execute only if multiple conditions are true. To achieve this, one option would be to use nested conditionals, such as the following:

external $;

string colorString;
bool likesRed = true;
bool likesBlue = true;
    
if (likesRed) {
    if (likesBlue) {
        colorString = "I have a wide taste in colors";
        $("#content").text(colorString);
    }
}

By placing the likesBlue conditional within the likesRed conditional in this way, we ensure that the code in the likesBlue block will execute if and only if both conditions are true.

Although nested conditionals can be used for such purposes, however, they tend to make code difficult to read, particularly when the conditionals involved are complex. An alternative is to use the logical AND operator “&&”. Let’s replace our nested conditional with:

if (likesRed && likesBlue) {
    colorString = "I have a wide taste in colors";
    $("#content").text(colorString);
}

An “&&” statement takes two operands, which will normally both be Boolean expressions. Assuming they are, the statement returns true if both operands are true, and false otherwise. Thus the code above has the same effect as the earlier nested conditional: the code block executes if and only if both likesRed and likesBlue are true. The “&&” conditional is easier to read than the nested conditional, however, so is for that reason preferable.

JS++ contains two other logical operators in addition to “&&”: the OR operator “||”, and the NOT operator “!”. “||” is a binary operator like “&&”: it takes two operands. Assuming both are Boolean expressions, the statement returns true if at least one operand is true, and false otherwise. “||” is useful in cases where you want some code to execute if either one condition is true or another is:

if (likesRed || likesBlue) {
    colorString = "I like at least one color";
    $("#content").text(colorString);
}

“!” differs from “&&” and “||” in that it is a unary operator: it takes a single operand. It returns true if the operand is false, and false if the operand is true. For example:

if (!likesRed) {
    colorString = "I do not like red";
    $("#content").text(colorString);
}

Note: Although the operands governed by “&&” and “||” will normally be Boolean expressions, they don’t have to be. To cover cases where the operands are non-Boolean, “&&” and “||” are more precisely defined as follows: an “&&” statement returns false if the left operand is false; otherwise it returns the value of the right operand. An “||” statement returns true if the left operand is true; otherwise it returns the value of the right operand.

Switch statements

Sometimes you need your program to handle various different possibilities and to execute different code in each. Although you could achieve this by using a conditional with multiple else if statements, it is often simpler is to use a switch statement. A switch statement evaluates an expression and compares its value with one or more case expressions; if one of these case expressions provides a match, some associated code is executed.

Switch Diagram

Let’s take an example:

external $;

string favoriteColor;
string colorComment;
favoriteColor = "green";
    
switch (favoriteColor) {
    case "red":
        colorComment = "red is fantastic";
        break;
    case "blue":
        colorComment = "blue is wonderful";
        break;
    case "green":
        colorComment = "green is magical";
        break;
    case "yellow":
        colorComment = "yellow is brilliant";
        break;
    default:
        colorComment = "I have no favorite color";
        break;
}
    
$("#content").text(colorComment);

In this example, the switch statement compares the value of the string favoriteColor with the various case expressions listed. When it finds a match, it executes the associated code. Since the value of favoriteColor is “green”, the switch statement executes the code associated with that case: the string colorComment is set to “green is magical“.

What is the purpose of the break and default keywords? The break keyword is very important because it’s needed if you want to prevent so-called “fallthrough”. Fallthrough happens when a switch statement executes the code associated with one or more cases after the matching case. For example, if you remove the break at the end of the green case, the switch statement will go on to set colorComment to “yellow is brilliant“. In some rare situations you may want fallthrough of this sort; if so, you would intentionally omit break. (You would also be advised to add a comment explicitly indicating that the fallthrough was intended.) Usually, however, you will want to include break at the end of each case.

The code in the default clause is executed if none of the case expressions match the original expression. The default clause is optional: if you don’t provide one, then the program resumes execution at the first statement after the switch statement.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.