JavaScript Loops Explained
Tags: javascript, webdev, programming, productivity
Published: 2022-09-14 16:13:15

In JavaScript, we use loops when we want an easy way to handle repetition. In this article, we’re going to take a look at all the different ways we can create loops in our code — and we’ll consider the pros and cons of each method.

A way to think of a loop could be to think of giving commands to a robot. You could tell it to take 10 steps — and rather than issuing 10 separate commands, we can create a loop:
```js
let i;
for (i = 0; i < 10; i++) {
  document.write("Take one step!\n");
}
```
This is an example of a `for` loop. At first, this may be confusing — but we’ll break it all down in the next section! In this article, we’ll be reviewing many different kinds of loop statements, such as: `for`, `do...while`, `while`, `labelled statement`, `break statement`, `continue statement`, `for...in` & `for...of`. It’s worth noting that despite their differences in syntax — loops all essentially do the same thing: repeat an action a number of times. The situation dictates which type of loop is best suited.

## the for loop
As we’ve seen in the above example, a `for` loop will repeat until our condition evaluates to false. The logical structure is like so:
```js
for ([initialExpression]; [condition]; [incrementExpression])
  statement
```
We are first initializing the `initialExpression`, which usually initializes one or more loop counters, but the syntax even allows for more complex expressions such as variables. We next evaluate our `condition`, if _true_, the loop statements will execute. If _false_, the loop terminates.

Then the `statement` executes. When we wish to execute multiple statements, we use a block statement (`{ ... }`) to group them together. If present, the update expression `incrementExpression` is executed. Control then returns to evaluating the `condition`.

Let’s now return to our previous example:
```js
let i;
for (i = 0; i < 10; i++) {
  document.write("Take one step!\n");
}
```
Here we can see our `for` statement is counting the number of steps taken up to 10. The variable `i` will ensure we’re starting from the beginning by initializing to zero. Then it will check that `i` is less than the number we specify, which in our case is _10_. The `i++` is the count which will increment `i` by 1 after each pass through the loop. So our loop knows when to complete!

## do...while statement
A `do...whilestatement` will repeat until the condition evaluates to false. The structure is like so:
```js
do
  statement
while (condition);
```
It’s fairly self-explanatory, `statement` is always executed once prior to the condition being checked. And then again until the while condition returns _false_. We can execute multiple statements, using a block statement (`{ ... }`) to group them. If `condition` is _true_, the statement executes again. At the end of each execution, the condition is checked. When the condition returns _false_, the execution stops and control passes to the statement which follows `do...while`.

Let’s see an example:
```js
let i = 0;
do {
  i += 1;
  console.log(i);
} while (i < 10);
```
Here our `do` loop iterates at least once and then reiterates until `i` is no longer less than 10.

## while statement
A `while` statement executes its statements as long as a specified condition evaluates to _true_. Its syntax is as follows:
```js
while (condition)
  statement
```
If the condition becomes _false_, the `statement` within the loop stops executing and control then passes to the statement following the loop.

The condition test occurs before the `statement` in the loop is executed. And if the condition returns _true_, the `statement` is executed and the condition is tested again. If the condition returns _false_, execution will stop and control is passed to the statement following `while`.

And as with `do...while`, we can execute multiple statements using a block statement ({ … }) to group them together.

The following `while` loop will iterate as long as `a` is less than three:
```js
let a = 0;
let b = 0;
while (a < 3) {
  a++;
  b+= a;
}
```
Here with each iteration, the loop increments `a` and adds that value to `b`. Therefore, `a` and `b` take on the following values:

- After the first pass through the loop : `a` = 1 and `b` = 1
- And the second pass: `a` = 2 and `b` = 3
- And the third pass: `a` = 3 and `b` = 6

After completion of the third pass, the condition `a < 3` is no longer _true_, so that’s where our loop terminates!

**Note**: When you first start working with loops, you may accidentally create an _infinite loop_. This is when a loop condition never evaluates to _false_. The statements in the following `while` loop execute forever because the condition is never false:
```js
while (true) {
  console.log('Hi there!');
}
```
**CAUTION**: If you run this code — please be aware that it’s likely to crash your browser!! So make sure you’ve backed up your open tabs - if you want to see what happens.

## labelled statement

You can attach a `label` to any statement to serve as an identifier so you can refer to it elsewhere in your program. As an example, you could use a label to identify a loop, and then use `break` or `continue` statements to indicate whether a program should interrupt the loop, or continue its execution (we’ll take a look at these below).
```js
label :
   statement
```
he value of `label` may be anything you like (with the exception of a JavaScript reserved word). Then you provide the `statement` to execute.

So for example, you could use the label `totalLoop` to identify a `while` loop.
```js
totalLoop:
while (total == true) {
   doSomething();
}
```

## break statement
We use the `break` statement to terminate a loop or `switch`, or in conjunction with a labelled statement.

- When you use `break` without a label, it terminates the innermost enclosing `while`, `do-while`, `for`, or `switch` immediately and transfers control to the following statement.
- When you use `break` with a label, it terminates the specified labelled statement.

A `break` statement looks like this:
```js
break [label];
```
For example, let’s loop through an array until we find the index of an element _with_ the value of: `foundMe`
```js
for (let i = 0; i < a.length; i++) {
  if (a[i] == foundMe) {
    break;
  }
}
```
And let’s use break with a labelled statement:
```js
let x = 0;
let z = 0;
endLoops: while (true) {
  console.log('Outer loops: ' + x);
  x += 1;
  z = 1;
  while (true) {
    console.log('Inner loops: ' + z);
    z += 1;
    if (z === 10 && x === 10) {
      break endLoops;
    } else if (z === 10) {
      break;
    }
  }
}
```

## continue statement
We use the `continue` statement to restart a `while`, `do-while`, `for`, or `label` statement.

When you use `continue` without a label, it terminates the current iteration of the innermost enclosing `while`, `do-while`, or `for` statement and continues execution of the loop with the next iteration. This contrasts with the `break` statement, as `continue` doesn’t terminate the execution of the loop entirely. In a `while` loop, it jumps back to the condition. In a `for` loop, it jumps to the `initial-expression`.
When you use `continue` with a label, it applies to the looping statement identified with that label.

A `continue` statement looks like so:
```js
continue [label];
```
For example, the following code block shows a `while` loop with a `continue` statement that will execute when the value of `i` is three. So `n` takes on the values one, three, seven, and twelve.
```js
let i = 0;
let n = 0;
while (i < 5) {
  i++;
  if (i == 3) {
    continue;
  }
  n += i;
  console.log(n);
}
// 1,3,7,12
let i = 0; 
let n = 0; 
while (i < 5) { 
  i++; 
  if (i == 3) { 
     // continue; 
  } 
  n += i; 
  console.log(n);
}
// 1,3,6,10,15
```

## for...in statement
A `for...in` statement iterates a _specified variable_ over all the enumerable properties of an _object_. For each distinct property, JavaScript executes the specified statements. The syntax is as follows:
```js
for (variable in object) {
  statements
}
```
The following function takes as its _argument_ an _object_ and the _object’s name_. It then _iterates_ over _all the object’s properties_ and _returns a string_ that lists the _property names_ and their _values_.
```js
function get_names(obj, obj_name) {
  let result = '';
  for (let i in obj) {
    result += obj_name + '.' + i + ' = ' + obj[i] + '<br>';
  }
  result += '<hr>';
  return result;
}
```
For an object `food` with properties `lunch` and `dinner`, `result` would be:
```js
food.lunch = Sandwich
food.dinner = Lasagna
```
_Note_: Given that `for...in` _is built for iterating object properties_, it's not recommended for use with arrays — where the index order is important. For arrays, it’s better to use the more traditional `for` loop.

## for...of statement
A `for … of` statement creates a loop that iterates over iterable objects, such as `Array`, `Map`, `Set`, `arguments` and so on. The syntax is like so:
```js
for (variable of object) {
  statement
}
```
The below example shows the difference between a `for...of` loop and a `for … in` loop. While `for...in` iterates over property names, `for...of` iterates over property values:
```js
let arr = [10, 20, 30];
arr.greet = 'hello';
for (let i in arr) {
   console.log(i); // logs "0", "1", "2", "greet"
}
for (let i of arr) {
   console.log(i); // logs 10, 20, 30
}
```

## Summary
We’ve learned about many of the different loop statements, such as: `for`, `do...while`, `while`, `labeled statement`, `break statement`, `continue statement`, `for..in` & `for...of`. And we’ve looked at a number of examples highlighting ideal use cases for each type of loop. Whichever statements we choose to utilize, we’re now well equipped to add logic and reasoning to our programs.

## Conclusion
If you liked this blog post, follow me on [Twitter](https://twitter.com/RembertDesigns) where I post daily about Tech related things!
![Buy Me A Coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijinng8k7bf23v0o6gkj.png) If you enjoyed this article & would like to leave a tip — click [here](https://www.buymeacoffee.com/rembertdesigns)

### 🌎 Let's Connect

- [Portfolio](https://www.rembertdesigns.co/)

- [Twitter](https://twitter.com/RembertDesigns)

- [LinkedIn](https://www.linkedin.com/in/rrembert/)

- [Hashnode](https://rembertdesigns.hashnode.dev/)

- [Devto](https://dev.to/rembertdesigns)

- [Medium](https://medium.com/@rembertdesigns)

- [Github](https://github.com/rembertdesigns)

- [Codepen](https://codepen.io/rembertdesigns)