Page 91 - JavaScript
P. 91

A traditional for-loop


        A traditional for loop has three components:

            1.  The initialization: executed before the look block is executed the first time
            2.  The condition: checks a condition every time before the loop block is executed, and quits
              the loop if false
            3.  The afterthought: performed every time after the loop block is executed


        These three components are separated from each other by a ; symbol. Content for each of these
        three components is optional, which means that the following is the most minimal for loop
        possible:


         for (;;) {
             // Do stuff
         }


        Of course, you will need to include an if(condition === true) { break; } or an if(condition ===
        true) { return; } somewhere inside that for-loop to get it to stop running.

        Usually, though, the initialization is used to declare an index, the condition is used to compare that
        index with a minimum or maximum value, and the afterthought is used to increment the index:


         for (var i = 0, length = 10; i < length; i++) {
             console.log(i);
         }




        Using a traditional for loop to loop through an array


        The traditional way to loop through an array, is this:


         for (var i = 0, length = myArray.length; i < length; i++) {
             console.log(myArray[i]);
         }


        Or, if you prefer to loop backwards, you do this:


         for (var i = myArray.length - 1; i > -1; i--) {
             console.log(myArray[i]);
         }


        There are, however, many variations possible, like for example this one:


         for (var key = 0, value = myArray[key], length = myArray.length; key < length; value =
         myArray[++key]) {
             console.log(value);
         }


        ... or this one ...



        https://riptutorial.com/                                                                               48
   86   87   88   89   90   91   92   93   94   95   96