Iterating in JavaScript
Tags: javascript
Published: 2020-10-20 03:10:01

Last week I decided to create a cheat sheet of sorts for iterating over Arrays in JavaScript. Its aim was to list and explain briefly all of the most commonly used built in methods for iterating or looping over Arrays. As I was thinking of what I should write about this week, I kept coming back to the concept of iterating or looping and thinking about how core of a concept it is in programming as a whole. 

Indeed, looping is one of the first concepts taught in almost any language, and is generally the first big concept one has to wrap their heads around before progressing in learning how to program. I decided this week would be a great time to step back and gear a post toward those that are where I was about a year ago and just trying to wrap their heads around this concept. In the following post, I will be discussing the concept of iteration as well as looking at the ways in which we use it in JavaScript specifically. 

##What is Iteration?##

So if we want to talk about iteration (also known as looping) we have to know what it is first, right? Plainly, iteration is the process by which you do something repeatedly, generally with some kind of condition that stops the process. We encounter this kind of looping all the time, though less explicit in the real world. 

For a real world example, think of meal prep. Say you are making mashed potatoes and the recipe tells you peel them all. Now we as humans can infer that the recipe means for you to take each potato and peel it. In this instance you are performing an action (peeling) until a certain condition is fulfilled (there are no more unpeeled potatoes).

If we wanted to program this action we have to be a bit more specific. We can define an action `peelPotato()` which tells the computer how to do what we want. Unfortunately, computers cannot infer like humans can and so if we tell it `peelPotato()` it will do just that and peel exactly one potato. 

Now certainly we could count the number of potatoes that we have and then tell the computer `peelPotato()` that number of times, but what happens if the number of potatoes changes? We would have to rewrite our entire recipe program. Not to mention the fact that our program would quickly become messy and unwieldy if we do this. This is where iteration and loops come in. We can define a condition (number of potatoes) and tell the computer that it should perform `peelPotato()` for as long as that condition is true (we still have potatoes to be peeled). 

This example is a bit rough and lacking some detail, but I hope it manages to relay the idea well enough. So what are the various ways that we can loop in JavaScript? Let's go through them one by one below.

##`for`##

The `for` statement is the most basic and generic of all the looping statements. It is created using the keyword `for`, followed by three optional expressions (this is where the condition is specified), followed by a code block (this is where your action is). This might be a bit confusing without seeing it so lets look at the basic syntax below.

```javascript
for (let i = 0; i < 10; i++) {
  console.log(i);
}
```

Let's first look at the three optional expressions in parenthesis after `for`. First we are declaring a variable `i` and setting its initial value to `0`. This is going to be our counter variable that we will use to check our exit condition. 

The second expression `i < 10` is our exit condition. Every time our loop starts, JavaScript will check to see if our counter variable `i` is less than `10`. If it is, we will loop another time - if it is not, we will break out of our loop and continue to the rest of our program.

The third expression `i++` is pretty simple. It tells our program to add `1` to the value of our counter at the end of every loop. This lets us keep track of how many times we have gone through the loop and provides and updated value for our condition to check against at the start of every loop.

Finally we have the code block that is between `{}`. This is just the code that we want to execute every time we loop. You can put whatever you want here, but for this example we are just console logging the value of `i` on every loop. Let's see how we could use our potato example in a `for` loop.

```javascript
let potatoCount = 5;  // number of potatoes we have

// as long as our counter is less than our potatoes, peel away!
for (let i = 0; i < potatoCount; i++) {
  peelPotato();
}
```

Keep these basic concepts in mind as we continue. Many of the other methods utilize these same principles in different ways or for different situations.


##`while`##

A while statement is very similar to the `for` statement. The biggest difference is that it only takes a single condition which it will check before every loop. If the condition evaluates to true, the loop will continue - if false, it will exit. 

You can even create a `for` loop using a `while` by creating your own counter variable - you just have to make sure to increment it yourself. The biggest advantage to using `while` is that it allows you to use `boolean` (true and false) values as a condition. Let's take a look at some examples!

```javascript
// basic while loop with boolean
let loop = true;

while(loop){
  console.log("We're looping!")
}

// mimicking a for loop
let counter = 0;

while (counter < 5){
  console.log(counter);
  counter++;
}

// potato example
while(hasPotatoes){
  peelPotato();
}
```

##`do...while`##

The `do...while` loop is almost identical to the `while` loop. The only difference is that the code to be executed comes first and is run before the condition is checked. This means that the code will always execute at least once, even if the condition starts false. This loop is really great for when you have some code that you know needs to run at least once, but might need to run more than once. Example time!

```javascript
// basic do...while
// even though i starts not greater than 0, this code will still 
// run one time
let i = 0;

do {
  console.log(i);
} while (i > 0);

// potato example
// careful, this will peel at least one time even if we have no 
// potatoes!
do {
  peelPotato();
} while(hasPotatoes);
```

##Conclusion##

There you have it, the three most common ways in which we are able to iterate in JavaScript! I hope that if iteration is a concept that you have been struggling with as start your programming journey, that this explanation helps you understand a bit better. While you might be new to programming, never be afraid to take a look at some documentation. If you want to learn more you should check out the docs [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements). The iterators I talk about here are under the `Iterations` section, and you'll even find some more advanced ones that I didn't cover. Good luck and happy coding!