JavaScript Flow Control

In this section of the tutorial, we will discuss JavaScript Flow Control and its uses which is important to instruct the program to execute a code only under certain conditions.

In JavaScript, a user can input and perform calculations and tasks and give the output using some decision-making capabilities which comes in the form of decision-making statements and loops in JavaScript. Decision-making is done based on the information gathered and analyzing certain conditions as to whether they are true or false.

There are many such statements and looping algorithms used in JavaScript, the most commonly used ones which we will discuss in this tutorial are if statement, else and else if statements, switch statement, for loop, for…in loop, while and do-while loops, and break and continue statements.

The if Statement

In JavaScript, the if statement is the most used decision-making statement. It is written in plain English language which makes it easy to understand and readable to even a non-technical person.

Example:

if (a>b)

{

   console.log("a is greater than b = "+a);

}
  • Here, if statement is used to check a condition whether a is greater than b or not.
  • If the condition is found to be true then the console.log function is executed.
  • Otherwise, the program skips the if statement and moves to the next line of code.

We will again use a code example to understand the working of the if statement.

Example:

<html>
<head>
<title>Flow Control Examples</title>
<script type="text/javascript">

if (Temperature < 0)
{
 document.write(“Temperature is below freezing point of water”);
}

if (Temperature == 100)
{
 document.write(“Temperature is at the boiling point of water”);
}

</script>
</head>
<body>
</body>
</html>

Similarly, in the above example, if both the conditions are found to be true, then the statements inside the if statement are executed. Otherwise, the if statements are skipped.

The else and else if Statements

else Statement

In JavaScript, a user can encounter situations where he wants to execute one set of code if a certain condition is true and he wants to execute a set of code if the condition is false.

In such scenarios, we use an else statement after the if statement to achieve the condition.

Example:

<html>
<head>
<title>Flow Control Examples</title>
<script type="text/javascript">

if (Temperature < 0)
{
 document.write(“Temperature is below freezing point of water”);
}

else
{
 document.write(“Temperature is not below freezing point of water”);
}

</script>
</head>
<body>
</body>
</html>
  • Here, if statement is used to check a condition whether Temperature is below 0 or not.
  • If the condition is found to be true then the document.write() function is executed.
  • Otherwise, the program skips the if statement and moves to the else statement, and execute the code inside it.

else if Statement

JavaScript also allows the use of multiple conditions at once in if else statement. Where it simply adds another if else statement inside the else statement of the outer statement. This kind of bundled statement is known as an else if statement.

We will take a code example to understand the else if statement.

Example:

<html>
<head>
<title>Flow Control Examples</title>
<script type="text/javascript">

if (Age >= 0 && Age <= 20) // condition 1
{
 document.write(“Age is between 0 and 10<br />”);
 if (Age == 10) // condition 2
 {
 document.write(“Age is 10 years.”);
 }
}
else
{
 document.write(“Age is NOT between 0 and 20.”);
}

</script>
</head>
<body>
</body>
</html>
  • Similarly, in the above example, if condition 1 is found to be true, then the flow control enters the if loop and checks condition 2.
  • If condition 2 is found to be true, then the document.write() function is executed.
  • If both the conditions are found false, then the flow control moves to the else statements and the document.write() function inside it is executed.

The switch Statement

In JavaScript, when a user wants the value of an exact variable for a large number of possible values, here we use a switch statement.

A switch statement can have the following four important elements in its syntax:

  • Test expression
  • Case statements
  • Break statements
  • Default statements

We will understand the working syntax with the help of a code example given below.

Example:

switch (Name)
{

 case “Tom”:
   document.write("Tom is a good cat");

 break;

 case “Jerry”:
   document.write("Jerry is a good mouse");

 break;

 default:
 document.write("Choose a correct name");

 break;
}
  • Here, the keyword switch is used to test the variable Name. We can put any valid expression in the place of the variable Name.
  • Keyword case is used to define different cases, i.e. Tom and Jerry.
  • If a user enters either of the two cases, the flow on control will be switched to the matched case.
  • Once the case is found and matched, the code statement inside it is executed.
  • At a situation when the user enters an irrelevant case, the flow of control shifts to the default case, which informs the user about the irrelevancy of the case.
  • At every instance, we can see a keyword break, this statement breaks out of the switch statement once any of the cases is found.

The for Loop

In JavaScript, when a user wants to repeat or iterates a block of code for any given number of times. This can be achieved by using a loop called for loop.

Like the if and switch statements, for loop too have a well-defined logic inside it, which checks the conditions then moves the flow control forward, otherwise, it breaks the loop and moves to the next line of code.

We will understand the working syntax with the help of a code example given below.

Example:

<html>
<head>
<title>Flow Control Examples</title>
<script type="text/javascript">

for (var i = 1; i <= 10; i++)
{
 document.write(“Test Loop”);
}

</script>
</head>
<body>
</body>
</html>
  • Here, just when the flow control enters the for loop, the first part of the loop initializes or assigns a value to the variable i. This initialization part is executed only once during the lifetime of the loop.
  • In the next part, following the semicolon, it has the test condition which checks whether the value entered by the user is smaller than or equal to 10 or not.
  • If the condition is found true, then the flow control moves to the next part following the semicolon. Here the code will be checked repeatedly until the condition becomes false and the loop breaks itself.
  • In the next part, the increment operator which is a type of Arithmetic Operator in JavaScript Operators, it is used which increases the value of after each iteration. Here, a decrement operator is also used to decrease the value after each iteration.
  • Once all the conditions are found to be true, the flow control enters the braces and executes the code statement inside the loop. The iteration will happen until the condition is true.

The for…in Loop

In JavaScript, when a user wants to loop through each element in the array without already defining how many elements the array actually contains. This kind of operation can be performed using for…in loop. A for…in loop can also be used with objects which we will discuss in the tutorial later in detail.

It minimized the effort of the user and enables to declare the number of elements an array can hold in runtime as it loops through or automatically moves to the next index after each iteration.

We will understand the working syntax with the help of a code example given below.

Example:

<html>
<head>
<title>Flow Control Examples</title>
<script type="text/javascript">

for (index in arr1)
{
 document.write(“Test Loop”);
}

</script>
</head>
<body>
</body>
</html>
  • Here, a variable index is declared prior to the loop which will be automatically replaced with the next index value in the array after each iteration.
  • arr1 is the name of the variable holding the array, here a variable behaves like an array with the help of the for…in loop.
  • For each iteration, the flow control will enter inside the braces and executed the block of code.

The while Loop

In JavaScript, when a user wants to execute a set of code statements but if he is unsure of how many times the loop will be iterated, then in such scenarios we use a while loop.

We will understand the working syntax with the help of a code example given below.

Example:

<html>
<head>
<title>Flow Control Examples</title>
<script type="text/javascript">

var i = 100;

while (i != 100)
{
 document.write("Test Loop");
}

</script>
</head>
<body>
</body>
</html>
  • Here, variable i is assigned a value 100.
  • In the next line, while loop will start working by checking the test expression inside the parenthesis.
  • If the condition is found to be true, then the flow control will move inside the braces and executes the document.write() function.
  • The while loop will iterate the loop again and again until the test expression becomes false.
  • Once, the test expression is found false, the loop breaks, and the flow control will be moved to the next line.

The do…while Loop

In JavaScript, if a user wants to execute a code statement once irrespective of whether the test expression is true or false, then this can be achieved by using a do…while loop.

A do…while loop works by executing the code statement before testing the test expression, if found true it iterates and keeps on executing the code statement. Just when the test expressing becomes false, the loop breaks and the flow control moves to the next line of code.

We will understand the working syntax with the help of a code example given below.

Example:

<html>
<head>
<title>Flow Control Examples</title>
<script type="text/javascript">

var i = 100;

do
{
 document.write("Test Loop");
}
while (i != 100)

</script>
</head>
<body>
</body>
</html>
  • Here, variable i is assigned a value 100.
  • In the next line, keyword do will start working by executing the code statement inside the braces.
  • After that, the test expression will be checked inside while statement, if the condition is found to be true, then the flow control will reverse and move inside again and executes the document.write() function.
  • The do…while loop will iterate the loop again and again until the test expression of the while statement becomes false.
  • Once, the test expression is found false, the loop breaks, and the flow control will be moved to the next line.

The break and continue Statements

break Statement

In JavaScript, a break Statement is used to stop the execution of the code and moves the flow control to the line next to the closing braces of the switch statement.

break Statement can also be used as a part of for and while loops if we want to exit the loop at any point of iteration.

We will understand the working syntax with the help of a code example given below.

Example:

switch (Name)
{

 case “Tom”:
   document.write("Tom is a good cat");

 break;

 case “Jerry”:
   document.write("Jerry is a good mouse");

 break;

 default:
 document.write("Choose a correct name");

 break;
}
  • Here, the keyword switch is used to test the variable Name. We can put any valid expression in the place of the variable Name.
  • Keyword case is used to define different cases, i.e. Tom and Jerry.
  • If a user enters either of the two cases, the flow on control will be switched to the matched case.
  • Once the case is found and matched, the code statement inside it is executed.
  • At a situation when the user enters an irrelevant case, the flow of control shifts to the default case, which informs the user about the irrelevancy of the case.
  • At every instance, we can see a keyword break, this statement breaks out of the switch statement once any of the cases is found.
  • After the break statement is executed, the flow control is moved outside the braces of the switch statement to the next line of code.

continue Statement

Just opposite to the function of a break Statement, we can also use a continue statement that restricts the flow control to leave the loop and starts executing the next iteration of the loop.

We will understand the working syntax with the help of a code example given below.

Example:

<html>
<head>
<title>Flow Control Examples</title>
<script type="text/javascript">

var TemperatureFahren,i;

 if (isNaN(TemperatureFahren[i]))
    {
      alert(“Data ‘“ + TemperatureFahren[i] + “‘ at array index “ +
             i + “ is invalid”);

      continue;
    }

</script>
</head>
<body>
</body>
</html>
  • Here, the if statement is used to convert all the values to TemperatureFahren.
  • During the iterations, if the user hits any invalid item of data in the array, the user will be notified using the alert() function.
  • Then the continue statement will be executed, which will again restart the iteration of the if statements and continue with the next item.

In the next section of the tutorial, we will discuss Strings in JavaScript and its uses to assign a variable with no character or one character or a combination of characters inside a single or double quote.