How to use a for loop in real world coding

How to, and why use a for loop in real world coding, a beginners guide

Posted by Ervin Adams on March 28, 2022

Although there are different types of loops used in programming, In my opinion the most common loop used is the for loop. In this example you will see a basic for loop and another simple example of how it is used in real world coding jobs using JavaScript.

Loops are used to execute a piece of code repeatedly. For instance, a for loop will repeat until a specific condition evaluate to false.

Below is an example of a for loop:

for(let i=1; i<=10; i++) {
     document.write("<p>The number is " + i + "</p>");

The above example defines a loop that starts with i=1. The loop will continue until the value of variable i is less than or equal to 10. The variable i will increase by 1 each time the loop runs. Therefore, the loop will run until i gets to 10 then stop.

Now that you have seen the example let's take a look at an example of what it could be used for in real world on the job coding. 

You may have a collection of data stored in an array that you are instructed to display in a list on the company's web page for example. Let's say it is a list of company core values.

You can store these values in an array like below:

const coreValues = [

Now loop through the list like below:

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

You might ask why not just do it like this:

    document.write('<li> Integrity </li> <li> Honesty </li> <li> Fairness </li> <li> Accountability </li> <li> Teamwork </li>');

That would be a good question, however sometime you do not have direct access to the collection of data. The data might be coming from an external source. Also there might be hundreds of data within the collection, it would not be practical to write all of it one by one.

So, hopefully that was helpful in trying to understand how loops are used in real world situations.