JavaScript Loops

JavaScript Loops

Loops are used to repeatedly run a block of code over and over again until a condition has been reached. This is often the case when working with arrays. You would want to loop through all the data and perform some kind of action on them. JavaScript offers several ways to run loops.

In terms of best practices and conventions, for loops are for a known number of iterations and while loops are to be executed until their intended job is done.

For Loops

A for loop is made 3 important parts.

Initialization: The starting point of the counter.
Test Statement: Set the end point of the counter. Test to see if the counter has been reached. If it has exited the loop. If not run the code inside the loop until it does.
Iteration Statement: Amount to increase or decrease your counter by.

For Loop Syntax

for ([initialization]; [test condition]; [iteration statement]) {
   // Statement(s) to be executed if test condition is true

For Loop - Examples

Count To 10

document.write("Count to 10.." + "<br />");       
for(var count = 1; count <= 10; count++) {
document.write(count + " ");

Lets modify this a little to be a count down timer for a rocket ship.

Countdown Timer

document.write("Starting Countdown.." + "<br />");       
for(var count = 10; count >= 1; count--) {
document.write(count + " ");
document.write("Blast Off!!!!!");

The most common use of a 'for loop' is to loop through an array.

Loop Through An Array

var fruitArray = ["Banana", "Apple", "Grape", "Orange", "Cherry"];

for (let i=0; i< fruitArray.length; i++) {
document.write(fruitArray[i] + "<br/>"); 

JavaScript While Loop

This one loops through a block of code as long as a specified condition is true.

While Loop Syntax Example

while (condition) {
// code block to be executed

While Loop Example

var c=0;
while (c < 25) {
Be Careful of the infinite loop.
An infinite loop will keep running forever. If you accidentally make one you can crash your browser or computer. In the above code if you forget to increase the variable used in the condition, the loop will never end. A loop can be terminated with the break keyword.

Break Out of a Loop Example

// Set a condition to true
const iceCapsAreMelting = true;
let polarBearsLeft = 5;
// Initiate infinite loop
while (iceCapsAreMelting) {
  console.log(`There are ${polarBearsLeft} polar bears.`);
  document.write(`There are ${polarBearsLeft} polar bears.<br>`);
  // Terminate infinite loop when following condition is true
  if (polarBearsLeft === 0) {
    console.log("There are no polar bears left.");
    document.write("There are no polar bears left.");

Do…While Loop

Similar to the while loop except the block of code will run first, then the condition will be tested to see if it should run again.

Do While Loop Syntax Example

do {
    // code block to be executed
} while (condition);

Facebook Video