Learning JavaScript: Part 7: Loops

Learning JavaScript

JavaScript is an interpreted programming language commonly found in web browsers. First appearing in 1995, it has grown to be the de facto web programming language used in most websites and on many systems serving webpages.


One of the most common programming concepts that nearly all languages share is that of loops or looping. Some languages call the concept different names and have certain functionality to achieve it, but it exists as a nearly universally used concept.

In JavaScript, there are two main forms of loops: while and for.

While Loops

Screenshot 2018-09-22 14.09.44

Similar to conditional statements, a while loop runs any code found within it over and over again until the condition is no longer true.

Screenshot 2018-09-22 14.11.47

For Loops

Screenshot 2018-09-22 14.29.18

for statement is made up of four parts run in order:

  • Initial statement
  • Condition to check before each loop
  • Code inside the loop
  • Statement to run after each loop

For statements are the most commonly used in situations where the loop will have a fixed or known number of cycles. The initial statement, then, is often set to 0 or another value and acts as the counter for the number of loops.

The condition is what keeps the loop running. For as long as the condition holds true, the for statement will run. As soon as it is no longer true, the looping breaks.

Frequently, the last statement within the for statement will increase the counter created in the initial statement. In most cases, this will be a “++” increment or “–” decrement operator that works as a short hand to increase or decrease the value by 1 each time.

For Loops and Arrays

Screenshot 2018-09-22 14.15.10

One of the more common use cases for a for loop is with an array or other data structure where the length is known. Using a for loop to move through an array is easy because the variable used to control the loop can be used as the index to the array.

Because array positions start with 0, a for loop’s variable can also be set at 0 and increase by one per loop. As long as it is less than the length of the array, it will go through all of the values one by one.

For-In Loops

Screenshot 2018-09-22 14.38.41

JavaScript also allows for using a for loop using a for…in pattern. Instead of using a number for the control of the loop, it will run by setting some variable to the next value within it until there are no more available values.

The for…in pattern is the most useful for objects. Because objects have properties and not indexes where data can be found, the for…in loop can use the name of the property itself as an index to find a value.

Screenshot 2018-09-22 14.41.33

Codepen Example:

See the Pen Learning JavaScript: Part 7: Loops by Dan Cox (@videlais) on CodePen.

Relp Example:

Test on Relp.it! 

Mozilla Thimble:

Remix on Mozilla Thimble!