Conditional and Repetitive Structures in JavaScript
Simple Conditional Structure
Not all problems can be solved using sequential structures. When a decision needs to be made, conditional structures are used. In our daily life, we face situations where we must decide. “Do I choose race A or race B?” “Should I wear these pants?” “Do I visit website A or website B?” “To go to work, do I choose path A or path B?” “When scheduling a race, do I choose the morning, afternoon, or evening shift?”
These problems often combine sequential and conditional structures. When presented with a choice, we have the option to perform an activity or not.
In a simple conditional structure, there are activities for the true path and no activity for the false path. On the true path, there may be several operations, inputs, and outputs, including other conditional structures.
The if
statement in JavaScript determines which path to take. The condition must be enclosed in parentheses. If the condition evaluates to true, all instructions enclosed between the opening and closing braces following the if
statement are executed.
To provide conditions in an if
statement, we can use any of the following relational operators:
>
greater than>=
greater than or equal to<
less than<=
less than or equal to!=
not equal to==
equal to
Always remember that the condition in an if
statement should involve a variable, a relational operator, and another variable or a fixed value.
Another useful feature is the +
operator for strings:
document.write(name + ' is approved with a ' + note);
This allows us to make our code more concise. Previously, we might have written:
document.write(name);
document.write(' is approved with a ');
document.write(note);
Composite Conditional Structures
When presented with a choice, we may have the option to perform one activity or another. In other words, we have activities for both the true and false branches of the condition. The most important thing to remember is that only the activities of one branch (true or false) are executed, never both.
In a composite conditional structure, we can have inputs, outputs, and operations in both the true and false branches.
For example, the prompt
function returns a string. We can use this to determine which of two values is numerically larger.
In JavaScript, a variable can change the data type it stores throughout the program. Let’s see what happens when we ask which of two strings is greater.
We are dealing with a composite conditional structure because we have activities for both the true and false branches. The conditional structure is composed of the following code:
if (<condition>) {
<Instruction(s)>
} else {
<Instruction(s)>
}
This is the same as the simple conditional structure, except for the keyword else
and the block of code in braces {}
following it. If the condition is true, the block after the if
statement is executed. If the condition is false, the statement or block of statements after the else
keyword is executed.
Nested Conditional Structures
A conditional structure is nested when the true or false branch of a conditional structure contains another conditional structure.
Example: Write a program that asks for a student’s grades from the keyboard, calculates the average, and prints one of the following messages:
- If the average is >= 7, show “Excellent”.
- If the average is >= 4 and < 7, show “Good”.
- If the average is < 4, show “Fail”.
Comments in JavaScript
Two forward slashes //
are used to indicate a single-line comment:
// Convert string to integer
If we have multiple lines of comments, we can use the following syntax:
/*
Comment line 1.
Comment line 2.
*/
This allows us to create a block comment.
Logical Operators && (and) in Conditional Structures
The &&
operator represents the logical”an”. It is used when a conditional structure has two conditions that must both be true for the result to be true.
When we link two or more conditions with the &&
operator, all conditions must be true for the overall condition to be true and for the code in the true branch of the conditional structure to be executed.
Remember that the entire condition must be enclosed in parentheses.
The use of logical operators can often lead to shorter and more understandable algorithms.
Logical Operators || (or) in Conditional Structures
The ||
operator represents the logical”o”. If either condition 1 or condition 2 is true, the code in the true branch of the conditional structure will be executed.
When we link two or more conditions with the ||
operator, only one of the conditions needs to be true for the overall condition to be true.
Switch Structures
The switch
statement is an alternative to using if/else if
chains. It is useful in situations where you need to check if a variable is equal to a specific value. You cannot use it to check for greater than or less than.
The variable to be analyzed is placed in parentheses after the switch
keyword. Each value to be checked is specified after the case
keyword, followed by a colon and the instructions to execute if the variable matches that value.
It is important to include the break
keyword after each case to prevent fall-through. The instructions after the default
keyword are executed if the variable does not match any of the cases. The default
case is optional.
When using a switch
statement, remember to enclose string values in quotation marks:
case 'red':
document.bgColor = '#ff0000';
break;
To change the background color of the window, we assign a value to the bgColor
property of the document
object. The color is specified using three hexadecimal values representing the amount of red, green, and blue. In this case, we assign the value ff
(255 in decimal) to red, which is the maximum possible value, and 00
to green and blue. You can use any color charting software to generate these hexadecimal values.
Repetitive Structures (while loop)
So far, we have used sequential and conditional structures. Another important type of structure is the repetitive structure.
A repetitive structure allows us to execute an instruction or a set of instructions multiple times. A repetitive execution of statements is characterized by:
- The statements that are repeated.
- A test or condition check before each iteration, which determines whether the statements will be repeated again.
while loop
The while
loop first checks the condition. If it is true, the operations between the curly braces following the while
keyword are executed. If the condition is false, the program continues with the statement after the loop’s closing brace.
The block of code inside the loop is repeated as long as the condition remains true.
Important: If the condition always evaluates to true, we have an infinite loop. This is a programming error, as the program will never end.
The most challenging part of using a while
loop is defining the condition and the block of instructions to be repeated. For example, if we have the condition x >= 100
(where x
is a variable), it will not cause a syntax error. However, it is a logical error because the condition will be false the first time it is evaluated, and the block of instructions will never be executed.
There is no single recipe for defining the condition of a repetitive structure. It is a skill that is developed through practice and solving problems.