JavaScript For Loop

JavaScript For Loop

Loops in Javascript (for loop and while loop)

Loops execute a block of code a specified number of times, or while a specified condition is true.

Used when same set of instructions are required to be executed multiple times.

Two types of loops

1)      For Loop – Used when number of execution is known already in advance

2)      While loop – Used when number of times execution is fixed but not known in advance


In both the types of loops there exists a condition till which the loop will executes

For loop and while loop example code

<html>

<head>

 <script type="text/javascript">

 function ForStart()

  {

              var numberCollection = new Array(0, 1, 2, 3, 4 );

                var length = numberCollection.length;

                var total = 0;

                // initailize ; condition; increment/decrement

                for(var i = 0; i < length; i++)

                {

                   total += numberCollection[i];

                }

                // Answer should be 10

                alert("Total of the collection = " + total);

  }

/*    Decremet Whileloop helps faster iteration  */

  function WhileStart()

  {

              var numberCollection = new Array(0, 1, 2, 3, 4 );

                var i = numberCollection.length;

                var total = 0;

                // Condtion and decrement both in one line

                while(--i)

                {

                     total += numberCollection[i];

                }

                // Answer should be 10

                alert("Total of the collection = " + total);

  }

  </script>

</head>

<body>

  <b>Javascript Loops</b>

<button onclick="javascript:ForStart()"> For Loop </button>

<button onclick="javascript:WhileStart()"> While Loop </button></body>

</html



Some things to remember about javascript loops to enhance performance (In terms of exection speed of the loops)

1)  Use var at place of for loop. Makes it more efficient

 

var length = numberCollection.length;

for(var i =0 ; i< length; i++)

{
  some stuff 
}


for(var i = 0; i < length; i++)
{  

}

2)      Cache variables for collection lengths, count etc so that we donot need to traverse the collection eachtime


3)      Avoid use of global variables whenever possible

4)      Get object and store in a common variable outside while/for loops



 

var containerObj  = $(“#containerDIV”);

 for(var i=0 ; I <5; i++)
  {
     // Some actions related to container  
  
}

 

)   While loops can be much faster when using decrement method

while(--i) {   //execute some actions    }

Currently rated 2.5 by 4 people

  • Currently 2.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5