7/15/2018

Learn Control Flow in Javascript(While, Do-While, For, For/in Loop)

Control flow in javascript is similar to C, C++ or any programming language. Now question is why we need Control flow in javascript or any other programming language, the reason is very simple as we all know that programs are groups of code and software are groups of programs so in a program there is a block of code we have to execute again and again and for saving space we can not write the code again and again to avoid this problem we use Control flow to control flow or block of code instead of writing again and again in programming language. In this tutorial, we will understand Control flow in details with complete syntax and example but before starting tutorials I just want to clear one doubts here in other programming languages we have only three Control flow (For Loop, Do...While Loop, and While Loop) and in Javascript we have one extra Control flow (For - in Loop), yes we have total of four loops in javascript or we can say that four Control flow statements in javascript. Basically, control flow controls the flow of programming and with the help of Loop avoid the repetitive code.

So in this tutorials, we are going to learn the Javascript Control Flow Structures or For Loop control flow javascript or For-In Loop control flow javascript or While Loop control flow javascript or Do-While control flow javascript in depth with complete explanation.

What are we going to learn?


  1. Control Flow
  2. What is Loop
  3. Types of Loops
  4. For Loop 
  5. For – in Loop
  6. While Loop
  7. Do-While Loop
  8. Syntax of Loops
  9. Examples of Loops
  10. Author Bio


Note: I just want to clarify that there is a big difference between Control flow and Conditional Statements tutorials in Javascript. If you don't know about conditions statements I suggest you have to read the Conditional Statements in-depth article before reading this article. this will helps you a lot to understand about flow control flow in javascript.

Control Flow


When a block of code needs to be executed many times with a different value, Then Control statements are required, According to a condition that is satisfied. Basically, Loops are there to avoid the repetitive code.

Loop Learn Control Flow diagram in Javascript
Image Source: Wikipedia


What are the Loops?


In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached. Typically, a certain process is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number or not.

Types of Loops or Loops in JavaScript are:


  1. For Loop 
  2. For – in Loop
  3. While Loop
  4. Do-While Loop

1. For Loop:

For loop is there to execute a block of code multiple times, For Loop is one of the best examples of a control flow of programs in programming statement in Javascript. Below is the syntax of FOR LOOP

Syntax:

for (statement 1; statement 2; statement 3)
{
    code block
}

Statement 1 is Checked or executed once before the execution.
Statement 2 Specify the condition of execution of code.
Statement 3 is executed every time until the specified condition is true.

For example:

for (i = 1; i <= 100; i++)
{
    text += "Value of i is " + i + "<br>";
}

Here i=1 is the statement1 which is executed once when execution of for loop will be started. Basically, we will use this to initialize that variable used by the loop.
I <=100 is statement 2 which is the basic condition that statements will be executed until the value of i will be 100.
i++ is the statement three which is executed every time when control satisfy the defined condition and I will increment by 1 every time.

For Loop Example:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Loops</h2>
<p id="ForLoopdemo"></p>
<script>
var number = "";
var n;
for (n = 0; n < 10; n++) {
    number += " Number is " + n + "<br>";
}
document.getElementById("ForLoopdemo").innerHTML = number;
</script>
</body>
</html>

We can omit these statement:

1.) Statement 1 can be omitted:

You can omit the statement 1 as it is optional for us, You can write it like:

Example:
             Initialize the variable before loop started.
           var Total = 0;
            var i = 1;
           for ( ; i < = 100; i++)
            {
             Total = Total + i;
             }
alert("Sum = " + Total);

2.) Statement 2 can be omitted:

As statement 2 is optional loop will work fine but you can put a break inside the for loop otherwise it will execute infinite times. Initialize the variable before loop started.

Example:

           var Total = 0;
            for (var i = 1 ; ; i++)
            {
             Total = Total + i;
              Break;
             }
             alert("Sum = " + Total);

3.) Statement 3 can be omitted :

  • If you don’t write the statement 3 but it can be incremented inside the for a loop.
  • if you don’t define any of the increment or decrement in the variable it will be executed only once.
  • Initialize the variable before loop started.

Example:

           var Total = 0;
           var i = 1;
           for ( ; i < = 100;)
            {
             Total = Total + i;
             i++;
             }
           alert("Sum = " + Total);

2. For-In Loop

the for..in loop is executed object's properties.

Syntax

for (variablename in object)
{
   code Block;
}

here in For-In Loop each time one property of the object is assigned to the variable and loop continues until object’s properties are exhausted.

Example

<!DOCTYPE html>
<html>
<body>
<p id="ForIn"></p>
<script>
    var book = {AuthorName:"Suman", bookName:"Tutorial", age:25}; 
    var bookProperties = "";
    var attributes;
    for (attributes in book) {
        bookProperties += book[attributes] + " ";
    }
    document.getElementById("ForIn").innerHTML = bookProperties;
</script>
</body>
</html>

3. While Loop

while loop will execute the block of code until the condition we specified is true. When the control comes to condition and found that condition is false control comes out of the loop and execute the exact next statement after the while loop.
While Loop firstly checks the condition then statements are got executed.

while (var < lastvalue)
{
block of code;
}

Example:

<html>
<body>
<script type="text/javascript">
var n=0
while (n<10)
{
document.write("Value of n is " + n)
document.write("<br />")
n=n+1
}
</script>
</body>
</html>

Here loop will be executed 10 times, the value of loop start for n=0 and condition will be true till n=9. When n=10 then the condition will be false and control comes out of the While loop.

While loop Control Flow in Javascript with gif example output


4. Do…While Loop

The do...while loop, you can also say it a variant of a while. Here the block of code will be executed at least once before testing the condition. So even if the condition becomes false though the code will be executed once.

do
{
Block of code;
}
while (var<=lastValue)

Example

<html>
<body>
<script type="text/javascript">
var n=0
do
{
document.write("value of n is " + n)
document.write("<br />")
n=n+1
}
while (n<10)
</script>
</body>
</html>

Tip: Always careful when you use control flow in programming cause if your desire conditions are not matched than your control flow may be infinite or you loop can be endless. so always twice checks the conditions of Loops and you can fix the flow of a program using loops.

Author Bio:


JavaScript Control flow Tutorials is provided by Suman Yadav. Thanks, Suman for the Awesome and Unique article. If you want to submit your article and want to be a member of our Programming With Basics Family Join us by sending a well-written article more information read Write for Us

2 comments:

  1. Basic and well defined article.Good job.

    ReplyDelete
    Replies
    1. Thank You, You Like It. Please Keep visit and Share.

      Delete