DEV Community

Martin Himmel
Martin Himmel

Posted on

JavaScript (ES5) Loops

This was originally posted on my site at https://martyhimmel.me on December 26, 2016. Like a number of others on dev.to, I've decided to move my technical blog posts to this site.

for Loops

for loops are probably the most common type of loop. Two common uses of the for loop are iterating over an array and doing something with each element, and iterating over an array to find a matching set of values. Here's the structure:

for (initial expression; condition; incrementing expression) {
  // do something on each pass
}
Enter fullscreen mode Exit fullscreen mode

The "initial expression" is an expression that marks the starting point of the loop. The "condition" is the ending point of the loop. The loop continues as long as the condition is true. Once the condition is false, the loop terminates. The “incrementing expression" is how the initial expression is changed on each pass of the loop (note: it doesn’t actually have to increment - it could decrement, increase by 2, etc.).

Here are a few examples of for loops. The first loop is the most common for loop that starts at the zeroth element (beginning) of an array and counts up.

// This will be used in all the examples.
var numbersAsWords = ['one', 'two', 'three'];

for (var i = 0; i < numbersAsWords.length; i++) {
  console.log(numbersAsWords[i]);
}
// one
// two
// three
Enter fullscreen mode Exit fullscreen mode

This loop starts at the last element of an array and counts down.

for (var i = numbersAsWords.length - 1; i >= 0; i--) {
  console.log(numbersAsWords[i]);
}
// three
// two
// one
Enter fullscreen mode Exit fullscreen mode

When a for loop is run, any expression in the "condition" part is calculated on every pass. When looping through a large number of elements, that could lead to performance issues. Using the previous two examples, if the numbersAsWords array had 100,000 elements, the length of the array would be calculated 100,000 times (on every pass). A way around this is to create an additional variable in the "initial expression” part of the loop and store the array's length. Then the array length is only calculated once at the beginning of the loop, instead of every pass through the loop. Here's an example:

for (var i = 0, arrLength = numbersAsWords.length; i < arrLength; i++) {
  console.log(numbersAsWords[i]);
}
// one
// two
// three
Enter fullscreen mode Exit fullscreen mode

for…in Loops

for…in loops are used to loop over the properties of an object. Here is the structure:

for (var prop in obj) {
  // do something
}
Enter fullscreen mode Exit fullscreen mode

The looping statement can be read as "for each property in an object." When using a for…in loop, you can access each property and value without knowing the specific name of the property. Remember, objects are sets of key/value pairs ("property": "value”). You can get the property name directly with prop (using the structure example) and the value by using bracket notation - obj[prop]. Here's an example:

var myWidget = {
  company: 'ACME',
  unitsSold: 42000,
  isModular: true
};

for (var prop in myWidget) {
  // log each property of the object as "property: value"
  console.log(prop + ': ' + myWidget[prop]);
}
// company: ACME
// unitsSold: 42000
// isModular: true
Enter fullscreen mode Exit fullscreen mode

while Loops

while loops continue to run until a condition is false. The structure is:

while (condition) {
  // do something
}
Enter fullscreen mode Exit fullscreen mode

for loops are great for iterating over a collection (e.g. an array). while loops can be used in the same way, but are generally better for doing something until user input or some sort of external condition says to stop.

An example of waiting for user input is the "game loop." Every game is built around the game loop. One example is while the player is playing, keep running the game - this is the most basic game loop, which would terminate by pressing the "Quit" button. Another example is while the character's hit points are above zero, keep fighting. An example with Tetris is while the blocks are below the top line, send the next block to the field. This list could go on indefinitely.

Here’s an example of a for loop variant:

var i = 1;
while (i <= 3) {
  console.log('Line ' + i);
  i++;
}
// Line 1
// Line 2
// Line 3
Enter fullscreen mode Exit fullscreen mode

And this is a game loop example:

var isPlaying = true;
while (isPlaying) {
  nextAction();
}
Enter fullscreen mode Exit fullscreen mode

Warning: It's easy to create an infinite loop using while (and do…while) loops. Make sure you have something in place to terminate the loop (an incrementor if looping a number variable, user input option to stop, etc.).

do…while Loops

do…while loops will do something once, then continue to run until a condition is false. The structure is a little different than a while loop, as the code is contained in the do block with the while containing only the condition.

do {
  // do something
} while (condition)
Enter fullscreen mode Exit fullscreen mode

A do…while loop is guaranteed to run at least once, becuase it runs the do code block before checking the condition. After the first run, it will keep looping over the do block as long as the condition is true.

Since the do block is run first without checking the condition, this can cause unexpected issues if you're not careful. Here are two examples of do…while loops. This one works properly:

var myArray = ['John', 'Jane'];
var i = 0;
do {
  console.log(myArray[i]);
  i++;
} while (i < myArray.length);
// John
// Jane
Enter fullscreen mode Exit fullscreen mode

This one fails silently:

var myArray = [];
var i = 0;
do {
  console.log(myArray[i]);
  i++;
} while (i < myArray.length);
// undefined
Enter fullscreen mode Exit fullscreen mode

The second example has some hidden dangers. At this point, it logs undefined to the console and nothing breaks. However, if you needed to manipulate the data in the array, it would break the script. Here's a modified version of the second example:

var myArray = [];
var i = 0;
do {
  console.log(myArray[i].toUpperCase());
  i++;
} while (i < myArray.length);
// Uncaught TypeError: Cannot read property 'toUpperCase' of undefined
Enter fullscreen mode Exit fullscreen mode

Adding .toUpperCase() (a string method) when calling an undefined array element breaks the script. For this reason, it's usually best to not use do…while loops unless you have a good reason to. More often than not, you can accomplish the same thing with a while loop.

Top comments (1)

Collapse
 
caseycole589 profile image
Casey Cole

my favorite while loop is the reverse

var i = arr.length;
while(i--) dosomething(arr[i]));