Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

9. Array() > Looping Over an Array, Backwards and Forwards

Looping Over an Array, Backwards and Forwards

The simplest (and arguably the fastest) way to loop over an array is to use the while loop.

Below, we loop from the beginning of the index to the end.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var myArray = ['blue', 'green', 'orange', 'red'];

var myArrayLength = myArray.length; /* cache array length, to avoid unnecessary 
                                    lookup */
var counter = 0; // setup counter

while (counter < myArrayLength) { // run if counter is less than array length
   console.log(myArray[counter]); // logs 'blue', 'green', 'orange', 'red'
   counter++; // add 1 to the counter
}

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

And now we loop from the end of the index to the beginning.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint