JavaScript Fundamentals: Loops
Tags: javascript, beginners
Published: 2021-08-13 15:16:49

Sometimes it's necessary to do something repeatedly. Often you'll find when coding, that it's required to complete a task multiple times. 

Take something as simple as counting. If we wanted to log to the console counting from one, to ten, it's very possible to manually type out the code to do so. 

```
console.log(1)
console.log(2)
console.log(3)
console.log(4)
console.log(5)
console.log(6)
console.log(7)
console.log(8)
console.log(9)
console.log(10)

```
That code then prints out our numbers:

```
1
2
3
4
5
6
7
8
9
10
```
As annoying as it is to write out console.log 10 times manually, imagine how annoying and repetitive it would be if it was necessary to count to a hundred, or a thousand. Doing so is not only tedious, but violates one of the most basic principles in coding, 'Don't Repeat Yourself.' Obviously, there has to be an easier, faster, and cleaner way to count one through ten. 

Enter Loops. 

## What are loops? 
Loops are not singular to JavaScript. As a programmer, you will come across them in almost all programming languages. 

Loops give us an easy way to do something repeatedly, and let us execute a block of code a number of times. 

There are a couple of different varieties of loops in JavaScript, today I'm going to talk about the `for` loop and the `while` loop, but if you want to know more about both those types, and others such as `do... while`, `for...in`, etc, here are a few of links to get you started. 

[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)

[freeCodeCamp](https://www.freecodecamp.org/news/javascript-loops-explained-for-loop-for/)

[codecademy](https://www.codecademy.com/articles/glossary-javascript#loops)

## The `for` loop

The `for` loop is the most common and basic loop. It has four parts. 

```
for (initialization; condition; iteration) {
       loopBody;
}
```
Let's break down what each bit means. 

### Initialization
Initialization, or what's commonly referred to as counter, is where the initial value of our counter is declared. It's an expression, and is often declared with the keyword `let`, as in `let i = 0`. Often you will see `i` declared as the counter variable, which is going to keep track of, and count through our loops as we make our way through them on each iteration. But, you can just as easily see a counter declared as `j` or, `counter` or whatever you might wish. 

### Condition
The condition, or the logical condition of our loop asks a question. If this condition is true, then we will proceed with looping through to the code block. If it is false, looping will cease. 

### Iteration 
A statement that is executed at the end of each iteration. Typically, this will involve either incrementing, or decrementing our counter, until our condition evaluates to false. It has to update on each iteration, otherwise we would be stuck in an infinite loop that would keep repeating for forever, until the browser eventually breaks. 

### Loop Body or Statement 
The loop body, or statement, is the code that is executed on every iteration, so long as our condition evaluates to true. 

## Example
But what does this all even mean when writing a for loop? Returning to our counter example, if we wanted to write our counter as a loop instead of `console.log()` it all, we could write it as follows: 

```
for (let i = 0; i < 11; i++){
   console.log([i])
}
```
This loop will produce the same result as our manual code. 

```
1
2
3
4
5
6
7
8
9
10
```
It's so much easier to write three little lines of code, versus the 10 we had to write before. 

What if we wanted to count backwards instead of forwards? Think for a moment how that might be possible. Using the template of our original code, what would be necessary to change in order to count back from 10 rather than to 10? 

Rather than starting our counter at 1, we could start at 10. Our condition can be flipped from `i < 11` to `i > 0`, and our i would have to decrement, `i--`

```
for (let i = 10; i > 0; i--) {
    console.log(`Countdown ${i}!`)
}
```

We could even, if we wanted, to slip in a little logic into our counter as well, so that if our variable evaluates to 0 within the loop, the message has a little more information. 

```
for (let i = 10; i >= 0; i--) {
    if (i === 0) {
        console.log(`BOOM! Liftoff! 🚀`)
    } else {
        console.log(`Countdown: ${i}!`)
    }
}
```

Will output: 

```
Countdown: 10!
Countdown: 9!
Countdown: 8!
Countdown: 7!
Countdown: 6!
Countdown: 5!
Countdown: 4!
Countdown: 3!
Countdown: 2!
Countdown: 1!
Countdown: 0!
BOOM! Liftoff! 🚀
```

### Another example
Often you'll find when trying to loop through say, an Array, the loop condition will look a bit different. 

Say we had an array of foods that we wanted to loop through instead of a simple counter. 

`let foods = ["strawberries", "pizza", "cake", "watermelon"]`

While it's possible to loop through the foods array using the same logic as counter: 

```
for (let i = 0; i < 4; i++){
    console.log(`I like ${foods[i]}`
}
```
We run into a bit of a problem if we added another food onto our foods array. Setting the condition to evaluate to a specific number, doesn't account for our array changing. Instead of hard coding a counter, often you will see the condition based upon the size, or length of an existing array, like so: 

```
for (let i = 0; i < foods.length; i++){
    console.log(`I like ${foods[i]}`
}
```

By rewriting our condition to test the length of the array, it will automatically update if we decide to add one food, or a hundred onto our array, or reduce our array to a single food. Every single time we run it, our loop will work. 

## The `while` loop
The `while` loop is slightly different to a `for` loop. Its structure is actually a bit similar to an `if` statement. And it runs through a block of code, so long as the condition evaluates to true. 

```
while (condition) {
    loopBody
}
```

Returning to our counter example, if we wanted to rewrite it as a `while` loop, we could write it as follows: 

```
let i = 1
while (i < 10) {
   console.log(i)
   i++
}
```
Which will output to the console: 

```
1
2
3
4
5
6
7
8
9
10
```

`while` loops are useful for when we don't really know how many times we need a block of code to run. We can write any `for` loop as a `while` loop if we wanted to. 

It's important to note that you have to remember to include the iteration statement within the code block. That is, telling the counter to increment or decrement. Plugging in:

```
let i = 1
while (i < 10) {
    console.log(i)
}
```
Will trigger an infinite loop, without the iteration statement of `i++`, and the loop will run forever. 

## Conclusion 
Loops are incredibly useful when it comes to programming. I hope reading a little bit about `for` loops and `while` loops has helped. If reading about the two types has whet your appetite, try exploring the other types of loops it's possible to use when writing in such a dynamic language as JavaScript, maybe even dive a little deeper into using break statements in loops, or continue statements. Try reading some of the mentioned resources, and playing as always in your console, to see what you can do!