Web Development

JavaScript Looping

JavaScript Looping is section 18 of Beginner’s Guide to JavaScript.

We introduced Looping with branching statement usage, but didn’t go much into details about how the loops create and functioned. Loops can execute a block of code a number of times. If you want to run the same code over and over again, each time with a different value, then the loops are the best option.

Most of the time loops are used with arrays. For example let’s say you have a array of cars where it included car names and you want to print all the names. One way to do this if follows.

[code languague=”js”] text += cars[0] + “
“;
text += cars[1] + “
“;
text += cars[2] + “
“;
text += cars[3] + “
“;
text += cars[4] + “
“;
text += cars[5] + “
“;
[/code]

But this is not the best way to do this. You see, this is code duplication and wasting too much of codes. Instead of that you can use a loop to execute this code segment, by changing the index number of the array each time.

[code languague=”js”] for (i = 0; i < cars.length; i++) { text += cars[i] + "
“;
}
[/code]

Easy, isn’t it?

There are several types of loops in JavaScript.

  • for – loops through a block of code a number of times
  • for/in – loops through the properties of an object
  • while – loops through a block of code while a specified condition is true
  • do/while – also loops through a block of code while a specified condition is true

Let’s look at each one of them.

The For Loop

The for loop is often the tool you will use when you want to create a loop. The for loop has the following syntax:

for (statement 1; statement 2; statement 3) {
code block to be executed
}

Statement 1 is executed before the loop (the code block) starts.

Statement 2 defines the condition for running the loop (the code block).

Statement 3 is executed each time after the loop (the code block) has been executed.

To demonstrate the three statements in the for loop, let’s take a simple example.

[code languague=”js”] for (i = 0; i < 5; i++) { text += "The number is " + i + "
“;
}
[/code]
  • Statement 1 sets a variable before the loop starts (var i = 0). Normally you will use statement 1 to initiate the variable used in the loop. This is not always the case, JavaScript doesn’t care. Statement 1 is optional.
    • You can omit statement 1 like when your values are set before the loop starts. [code language=”js”] var i = 2;
      var len = cars.length;
      var text = “”;
      for (; i < len; i++) { text += cars[i] + "
      “;
      }
      [/code]
    • You can initiate many values in statement 1 separated by comma [code language=”js”] for (i = 0, len = cars.length, text = “”; i < len; i++) { text += cars[i] + "
      “;
      }
      [/code]

 

  • Statement 2 defines the condition for the loop to run (i must be less than 5). Often statement 2 is used to evaluate the condition of the initial variable. This is not always the case, JavaScript doesn’t care. Statement 2 is also optional. If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
  • Statement 3 increases a value (i++) each time the code block in the loop has been executed. Often statement 3 increases the initial variable. This is not always the case, JavaScript doesn’t care, and statement 3 is optional. It can be omitted like when you increment your values inside the loop. Statement 3 can do anything like negative increment (i–), or larger increment (i = i + 15), or anything else. [code languague=”js”] var i = 0;
    var len = cars.length;
    for (; i < len; ) { text += cars[i] + "
    “;
    i++;
    }
    [/code]

The For/In Loop

The JavaScript for/in statement loops through the properties of an object.

[code languague=”js”] var person = {fname:”John”, lname:”Doe”, age:25};

var text = “”;
var x;
for (x in person) {
text += person[x];
}
[/code]

The While Loop

The while loop loops through a block of code as long as a specified condition is true. The code syntax goes like follows.

while (condition) {
    code block to be executed
}

If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser. Following is the while loop implementation. The code in the loop will run, over and over again, as long as a variable (i) is less than 10

[code languague=”js”] while (i < 10) { text += "The number is " + i; i++; } [/code]

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. Syntax goes as follows.

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

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested. Do not forget to increase the variable used in the condition, otherwise the loop will never end!

[code languague=”js”] do {
text += “The number is ” + i;
i++;
}
while (i < 10); [/code] So we had covered all the four types of loops in JS. So why there are so much loops. Let's compare them.

Comparing For and While

While loop is much the same as a for loop, with statement 1 and statement 3 omitted. The loop in this example uses a for loop to collect the car names from the cars array.

[code languague=”js”] cars = [“BMW”,”Volvo”,”Saab”,”Ford”];
var i = 0;
var text = “”;

for (;cars[i];) {
text += cars[i] + “
“;
i++;
}
[/code]

The loop in this example uses a while loop to collect the car names from the cars array.

[code languague=”js”] cars = [“BMW”,”Volvo”,”Saab”,”Ford”];
var i = 0;
var text = “”;

while (cars[i]) {
text += cars[i] + “
“;
i++;
}
[/code]

As you see, there is no much difference. You can use any type of looping technique depending on your situation, where it can implement very easily.


 

What’s Next?

Learn what is JavaScript Type Conversion

Join Our Newsletter Today

Stay updated with all latest updates.
Give it a try, you can unsubscribe anytime.
Subscribe
SUBSCRIBE NOW

About the author

Sandeep Likhar

Sandeep Likhar from Indore India, Blogger, eBook Designer and Founder of LetsDnD. Having five years of experience in industry as a Digital Publishing Expert and eBook Converter providing services to Authors, Publishers and distributors worldwide. Proficient in converting books into various formats HTML, epub, mobi, word, PDF including all major online platforms iTunes, Kobo, Kindle, Createspace, B&N, Smashwords and more.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz
DON’T MISS OUT!
Subscribe To Newsletter
Be the first to get latest updates and exclusive content straight to your email inbox.
Stay Updated
Give it a try, you can unsubscribe anytime.

Join Our Newsletter Today

Stay updated with all latest updates.
Give it a try, you can unsubscribe anytime.
Subscribe
SUBSCRIBE NOW