JavaScript Loops for Beginners

JavaScript Loops for Beginners

In the real world, repetitive actions are really what helps us get through the day. Think of the steps you take to work, or around the house: they are one step repeated a number of times, to get you where you are going.

In JavaScript, repetitive actions are possible with loops. At some point, you may need a script to run a piece of code several times, and that's where the power of looping really shines. Without loops, you'd be wasting a lot of time cutting and pasting a bunch of wasteful code.

What are loops?

Basically, loops are codes written to perform repeated tasks based on a condition that return either true or false.

Types of loops:

There are different types of loops to suite certain conditions and needs.

  1. The for loop.
  2. The while loop.
  3. The do...while loop.
  4. The for...in loop.
  5. The for...of loop.
  6. The infinite loop.

The 'for' loop:

The 'for' loop is used to repeat a task for a certain 'known' number of times. It is used when you are sure of how many times you plan to make the task repeat. The 'for' loop equally allows you to count either from top to bottom or bottom to top. It is mostly used to go through arrays.

Using real world examples you can safely say:

  • To be able to wipe the screen properly, wipe it 'for' 20 times.
  • For you to get the burger from the table, take steps 'for' 10 times.

These tasks has a specific number of repetition to perform the required task and once the number is reached the loop returns false and stops counting+

The parts of a 'for' loop:

The 'for' loop consists of four parts.

  1. Initialization: This happens one time in the loop. It makes the loop start.

  2. Test Condition: The test condition checks to see if the loop should do another cycle or not.

  3. Action: The action part is the code that is being repeated.

  4. Update: The update gives the accurate state or phase of the loop after each cycle.

Syntax:

for ([initialization]); [condition]; [update]) {
   Action;
}

//OR

for (var i = 0; i < 10; i++){
takeStep();
}

Code example explained:

  1. Let the count start at 0.

    'i' stands for integer but can equally be written as any other alphabet of your choice and we are using it to represent the variable.

  2. Check to see if 'i' is less than 10.

    If its less than 10, continue with the action but if its up to 10, then stop the action.

  3. Run the loop action code, which in this case means running the takeStep() function.

    The takeStep function is the third step in the loop. In here, is where all the actions needed to take a step are written. Once the action is done, we move to step 4 where we get to move to the next stage of the loop

  4. Increment i and go back to Step 2 to possibly start another loop cycle.

A 'for' loop counting down will look like this:

for (var b = 10; b > 0; b--)

This will start count at 10 down to 1 but if you want it to get to zero then you can do 'b >= 0' instead.

The 'while' loop:

Unlike the 'for' loop which is geared towards a specific number count, the 'while' loop is based on a condition. It starts by evaluating a condition to see if its true or not. If the condition is true, the code executes. If its false, the code will not execute.

'While' loops let you repeat code while a certain condition is true.

Using real world examples you can safely say;

  • While the baby is sleeping, get some rest.
  • While the windows are open, close the curtains.

With these examples, you can see that the second part, which is the action is only made to happen when the first part, which is the condition, is true.

Parts of a 'while' loop:

The 'while' loop has 2 parts.

  1. The test condition: This is the statement to watch out for. Checks to see if the loop should cycle.

  2. The Action: This the code to run when the statement is true.

Syntax:

while (condition){
Action;
}

//OR

While (babySleeps){
takeRest();
}

Code Example:

let n = 0;
while (n < 10) {
  n++;
}

The value of the variable is declared as zero. While n is less than 10, n increments.

##The 'do...while' loop:

The 'do...while' loop is closely related to the while loop but in the case of a 'do...while' loop, the action comes first before the conditional evaluation. The trick is, once the condition evaluates to true, the action repeats again not judging the fact that the action has been done before. But if the condition evaluates to false, then the code/action stops.

Using real world examples you can safely say;

  • Do rest while the baby sleeps.
  • Do close the curtains while the windows are open.

Parts of a 'do...while' loop:

The 'do...while' loop equally has 2 parts.

  1. The action: The code/statement that runs first before checking for a condition.

  2. The test condition: The condition checks if it should go for another round of loop. (Once the condition evaluates to true, the action is repeated)

Syntax:

 do {

   Action;

} while (condition);

//OR

do {

takeRest();

}while (babySleeps);

Code Example:

let i = 0;
do {
  i += 1;
  console.log(i);
} while (i < 5);

In the above code, the 'do...while' loop iterates at least once and reiterates until i is no longer less than 5.

The 'for...in' loop:

This type of loop is used on objects. The 'for...in' loop goes through all the properties of a given object. For each distinct property, JavaScript executes the specified statements.

Syntax:

for (variable in object)
  Action

Using the object car as example, the above syntax can be interpreted as: For "a property" In "the object car" display the value. Remember the property is a variable because it changes as well as its values.

Code Example:

function get_props(property, obj_name) {
  let result = '';
  for (let i in properties) {
    result += obj_name + '.' + i + ' = ' + property[i] + '<br>';
  }
  result += '<hr>';
  return result;
}

The function above takes property and the object's name as its argument. It then goes through all the object's properties and returns a string that lists the property names. Thus, for an object car with properties make as Ford and model as Mustang, result would be:

car.make = Ford
car.model = Mustang

The 'for...of' loop:

This type of loop is used to iterate over iterable objects (including Array, Map, Set, Arguments object and so on).

Syntax:

for (variable in object)
  Action

Don't be confused by the syntax looking same because, while 'for...in' loop iterates over property names, 'for...of' loop iterates over property values.

Code Example:

let arr = [ "spoon", "fork", "knife" "pot"];

    for (let i of arr) {
        console.log(i);
    }

// Output:
// spoon
// fork
// knife
// pot

For more code examples of the "for...of loop" on other iterable objects visit This article from freecodecamp

The Infinite loop:

It is pertinent to note that there is a possibility of an infinite loop. An infinite loop will never stop iterating until you add a break to it or it crashes your website. So beware. It is therefore recommended that you use 'break' to stop a loop once it meets the desired condition. Using break in your loop is also useful for user experience such that in a case where the user makes a choice from an array, the loop stops instead of going through the whole loop before stopping.

Code Example:

function doBreak() {
  var i = 0;

  while (i < 8) {
    if (i == 3) {
      break;
    }
    i += 1;
  }
return i;
}

The code above is illustrating 'break' in a 'while' loop. If i = 3, then break the the loop.

Conclusion:

Now we can see that repetitive tasks are possible in JavaScript and for every scenario has a suitable type for it.

Resources:

Headfirst JavaScript by Michael Morrison (A JavaScript book).

JavaScript Loops Explained: For Loop, While Loop, Do...while Loop, and More

Loops and iteration

JavaScript For/in For/of

If you liked this article, please give your reaction, comment and share. You can also reach me on Twitter