Javascript Loops

Today we are going to learn loops in javascript. Loops are mostly used to repeat the execution of certain statements. If you want to execute the same statement again and again number of times, instead of writing it number of times you can place it once in any of the loop iterating that many times. In this tutorial we will learn for loop, while loop and for/in loop.
Let’s learn by creating a simple webpage. Follow the steps.

  1. Create a folder named “sec2_ch2” on desktop.
  2. Now open a new notepad++ document and save it as “loops.html” inside the folder “sec2_ch2” just created.
  3. Write the following html code in it and open this “loops.html” page in a browser.
  4. <!DOCTYPE html>
    <html>
     <head>
      <title>Javascript Loops</title>
     </head>
     <body>
     </body>
    </html> 
    
    • Output of this code in shown below:
    • output_before_javascript_code
      fig 1

  5. Now we will start our javascript loops.
    • We know that javascript is to be written in
      <script>---</script>

      tags and script tag can be written in head as well as body section of the webpage.

    • So in this tutorial we will write all the code in body section.
      • So let’s start with for loop. Write the following code in body section.
      • <script>
        document.write("<b><i>for loop output</i></b> <br><br>");
         for(var i=0;i<10;i++)
         {
          document.write("Number " + i + "<br>");
         }
        </script>
        
        • The above code shows us the use of for loop.
        • Syntax of for loop encloses variable initialisation, condition checking and increment/decrement in a single line separated with semicolon.
        • The statements to be repeated are placed inside the curly braces.
        • Let’s understand how for loop executes.
          1. In the for statement, the variable i is initialised to zero for the first time. This initialisation is done only once.
          2. Next, the condition is checked. If it evaluates to true, the statement/statements in the curly braces are executed.
          3. After execution of the statements, the control goes to the increment/decrement statement and the value of the variable is incremented/decremented as specified in the loop.
          4. Then once again the condition is checked and statements are executed.
          5. The steps iii and iv are repeated till the condition evaluates to true. The loop will terminate once the condition has evaluated to true.
        • In the code above, the statement document.write(“Number ” + i + “
          “);
          will print the text given in it.
        • In this statement concatenation operator (plus sign) is used to concatenate the text Number and the value of i variable.
        • Brake tag is used to start every statement on a new line.
        • document.write(“for loop output

          “); statement is for our information.

        • Repeatition of the loop number of times is called iterations.
        • The output of above code is shown below:
        • for_loop_first_output_with_9
          fig 2

        • This output shows numbers only till 9 because once i increments to 10, the condition becomes false and hence the loop terminates, it cannot enter the curly braces to execute the statement.
        • To make the loop print numbers till 10, we need to change the condition from i<10 to i<=10. So that the condition remains true when i reaches 10.
        • The output of above code with condition i<=10 is shown below:
        • for_loop_second_output_with_10
          fig 3

      • Now let’s see while loop. Write the following code below the for loop inside
        <script>---</script>

        tags.

      • document.write("<br><b><i>while loop output</i></b><br>");
        var j=0;
        while(j<5)
        {
        document.write('Number ' + j + '<br>');
        }
        
        • The above code shows us the use of while loop.
        • In the syntax of while loop, initialisation is done first, before the loop starts. Then the while statement contains the condition and then the body of loop contains other statements that are to be executed along with the increment/decrement statement.
        • Let’s understand the execution of while loop.
          1. In the above code, first variable j is initialised to zero. This statement also is executed for the first time. i.e. only once.
          2. Next control goes to while statement and checks the condition. If the condition evaluates to true, the statements in the curly braces are executed and the variable is also incremented/decremented as stated in the code.
          3. Step ii above is repeated till the condition is true. Once the condition becomes false, the loop is terminated.
        • document.write(“
          while loop output
          “);
          statement is given for our information.
        • The statement document.write(‘Number ‘ + j + ‘
          ‘);
          is used for printing the statement. It is same as explained in for loop.
        • The output of while loop output is shown below:
        • output_of_while_loop
          fig 4

        • while loop output shows numbers from 0 to 4. If you change the condition from j<5 to j<=5, it will show numbers from 0 to 5.
      • Next is for/in loop.
        • For/in loop is used only with collections.
        • It’s syntax is not similar to the regular for loop.
        • Let’s see it practically.
        • As for/in loop works for collections, let’s declare an array and then use for/in loop to display all the elements of array. Write the following code below while loop in
          <script>---</script>

          tags.

        • document.write("<br><b><i>for/in loop output</i></b><br><br>");
          var people=["Sally","Bob","Steve","Jen"];
          for(x in people)
          {
              document.write(people[x] + "<br>");
          }
          
        • The above code shows us the use of for/in loop.
        • document.write(“
          for/in loop output

          “); statement is for our information.

        • We have declared an array named people that contains some names.
        • We want to display all the values in the array people.
        • If it had not been for loops we would had displayed every value in the array as shown below:
        • document.write(people[0] + “<br>”);
          document.write(people[1] + “<br>”);
          document.write(people[2] + “<br>”);
          document.write(people[3] + “<br>”);
          
        • But we can display all the values with loops with minimum code.
        • The code for displaying the array values using for/in loop is:
        • for(x in people)
          {
              document.write(people[x] + "<br>");
          }
          
        • Syntax for for/in loop does not need initialisation, condition and increment/decrement as in for loop.
        • As for/in loop can traverse only through collections, its for statement contains a variable that can get each and every value in the collection.
        • In the above shown loop, x is the variable used for traversal, in is the keyword indicating from where should x take the value and people is the actual collection (array) that contains the values to be displayed.
        • Let’s understand the execution of for/in loop.
          1. All collections start from zero(0) index, hence the variable x is by default initialised to zero(0). You can have any variable name.
          2. When the loop starts executing, the variable , in this case, x gets the value at zeroth index from people array.
          3. Now the value at index 0 in people array is displayed using the statement document.write(people[x] + “
            “);
          4. After executing the statements in curly braces, the variable x is auto-incremented. i.e. now x will become 1.
          5. Now the value at index 1 will be displayed.
          6. The statements iv and v will repeat until and unless all the array elements are not traversed.
          7. The output of for/in loop is shown below:

          for_in_loop_output
          fig 5

  6. Displaying array elements using for loop.
    • We can display array elements using for loop as shown below:
    • document.write("<br><b><i>displaying array elements using for loop</i></b><br><br>");
      for(k=0;k<people.length;k++)
      {
      	document.write(people[k] + "<br>");
      }
      
    • Here, in for loop, k is the variable used for traversal.
    • The condition used is
      k<people.length;

      The condition indicates that k is less than the length of the array people.

    • We know , in javascript, array is an object and objects have properties.
    • length is also a property of some objects like arrays and strings.
    • length when used with a string tells us the number of characters in that perticular string and when used with array tells us the number of values in that perticular array.
    • If you add or delete some values from an array, the length will change accordingly.
    • The statement document.write(people[k] + “
      “);
      will print the value at respective index k from array people.
    • Output of displaying array elements using for loop is shown below:
    • array_elements_using_for_loop
      fig 6

    • Now, just add one more name to the existing people array manually as shown below:
    • var people=["Sally","Bob","Steve","Jen","Tom"];
    • We have added a new name Tom to the array. Now reload the page, you will find that the name Tom has also appeared in the list of names.
    • This is because, length property of array counts all the values in the array.
    • The output is shown below:
    • output_of_for_loop_demostrating_length_prop
      fig 7

  7. Displaying array elements using while loop:
    • We can display array elements using for loop as shown below:
    • document.write("<br><b><i>displaying array elements using while loop</i></b><br><br>");
      p=0;
      while(p<people.length)
      {
      	document.write(people[p] + "<br>");
      	p++;
      }
      
    • Here, p is the variable initially intialised to zero(0). While declaring a variable var keyword is optional.
    • The condition in the while statement,
      p<people.length

      will traverse the whole array till the last element due to the length property as explained above.

    • The statement document.write(people[p] + “
      “);
      will print the element at perticular index in the array people.
    • The variable p will be incremented by 1 with every iteration.
    • Thus it will continue till the length of the array i.e. 5. But we have 5 elements in the array just now, because we had added a new name Tom in it previously. And our condition is
      p<people.length 

      that means p<5. Now if we have 5 elements and our condition is p<5, then how all the elements will be displayed?

    • This is because, in any array, elements are placed from index 0 and all the five elements will be completely filled in the array upto the index 4.
    • Now our condition is
      p<people.length

      , it means p<5. All the array elements will be traversed and displayed upto the index 4 and when p reaches 5, the condition will become false and the loop will be terminated.

    • In this way all the elements are displayed in the array.
    • The array elements displayed using while loop is shown below:
    • array_elements_using_while_loop
      fig 8

    • Now, if you again remove one of the element from the existing array of people, only that many elements will be displayed using any of the above loops. Try it and view the output yourself.

Thus we finished the demontration of loops in javascript.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -