JavaScript Loops
Tags: beginners, javascript
Published: 2019-12-29 10:19:07

---
title: JavaScript Loops
published: true
description: A beginners guide to loops using the JavaScript programming language
tags: beginners, javascript
series: FrontEnd Development Zero to Hero
---
When we talked about [_conditional statements_](https://dev.to/ziizium/javascript-conditionals-cjd) in the last post we learnt that __certain code are executed when a certain condition is met__ using constructs like `if` or `switch` statements. 

Technically speaking this is called _branching_ because the JavaScript interpreter follows a branching path through your source code.

Loops on the other hand, are those that bend that path back upon itself __to repeat portions of your code__.

We will discuss the looping statements in JavaScript accompanied with code examples.

_All screenshots are from <b>Firefox 71.0</b> and its Developer Tools. One particular feature in Firefox 71.0 that's worthy of mention is the <b>multi-line code editor</b> in the console._

<hr>

The following are the common looping statements in JavaScript:

* `while`
* `do/while`
* `for`
* `for/in`

###__`while`__

The `while` statement is JavaScript basic loop. The syntax is as follows:

```javascript
while (expression) {
  // statement
}
```

To execute the _statement_ the interpreter first evaluates the expression. If the resulting value of the expression is false, then the interpreter skips over  the statement  and moves on to the next statement in the program.

If the expression evaluates to true,  the interpreter executes the statement and repeats, jumping back to the top of the loop and evaluating expression again until the expression evaluates to false.

Simply put the __interpreter executes statement repeatedly while the expression evaluates to true__.

When you find yourself in a situation whereby __the expression does not evaluates to false, you have unknowingly created an infinite loop__.

__Infinite loops never ends__ hence the name _infinite_.

__To make sure the loop evaluates to false, ensure the expression at one point during the program execution evaluates to false__.

Let's have a look at an example.

```javascript
/**
  * The while code below will execute and
  * the numbers 0-9 will be printed in the console
  *
  */

// This is our expression
var counter = 0;

// we start the while loop
while (counter < 10) { // if the counter is less than 10
  
  // print the counter to the console
  console.log(counter);
  
  // Increments the counter value by one.
  // the expression counter++ is the same
  // as writing counter += 1. The "++" after
  // the counter variable is known as a post-fix
  // operator.
  counter++;
  
}
```

When executed in the console:

![A while loop in JavaScript](https://thepracticaldev.s3.amazonaws.com/i/m5xh2l9lj5gttrzlui2f.PNG)

###__`do/while`__

The `do/while` loop is __like a while loop, except that the loop expression is tested at the bottom of the loop rather than at the top__. This means that the body of the loop is always executed at least once. The syntax is:

```javascript
do {
  // statement
} while (expression);
```

Compared to the `while` loop, the `do/while` loop must always be terminated with a _semicolon_.

The `do/while` loop is less commonly used than `while` loop.

Let's have a look at an example.

```javascript
/**
  * The do/while code below will execute and
  * the numbers 0-9 will be printed in the console
  *
  */
// we define a counter variable
var counter = 0;

do {
  // print a number to the console
  console.log(counter);
  /**
    * Here we increment the counter variable
    * inside the expression. If we dont, it will 
    * result in an infinite loop because the counter
    * variable is zero and it will always be less
    * than ten.
    * 
    * If you want to have some fun change the ++counter
    * to counter++ and run the code. The output
    * in the console will be from zero to ten. Why? Its
    * an advanced concept of post-fix and prefix operators.
    */
} while(++counter < 10);
```

When executed in the console:

![JavaScript do while loop](https://thepracticaldev.s3.amazonaws.com/i/uf9hbmmg3vug6v33yk1i.PNG)

###__`for`__
The `while` loop and `do/while` loop have three things in common as demonstrated in previous examples. They are:

* a counter a variable &mdash; `var counter = 0;`
* a conditional test &mdash; `counter < 10`
* an increment &mdash; `counter++`

The `for` statement encodes each of these three manipulations as an expression and makes those expressions an explicit part of the loop syntax.

In the `for` loop syntax:
* The _counter variable_ becomes the _initialization variable_
* The _conditional test_ becomes _test_ 
* The _increment_ is still the _increment_

The syntax is:

```javascript
for (initialize; test; increment) {
  // statement
}
```

Now, we will rewrite our previous examples using a for loop.

```javascript
/**
  * This for loop example is short and precise
  * and the numbers 0-9 will be printed in the console
  *
  */
for (var counter = 0; counter < 10; counter++) {
  console.log(counter);
}
```

When executed in the console:

![JavaScript for loop](https://thepracticaldev.s3.amazonaws.com/i/z1avvqdm3n8x94u7aber.PNG)

This example is quiet basic and `for` loops can become more complex than this.

###__`for/in`__
The `for/in` loop uses the `for` keyword, but it is a completely different kind of loop than the regular `for` loop.

The `for/in` is used to __list properties of an object__.

The syntax is:

```javascript
for (variable in object) {
  //  statement
}
```

Time for some code. First we create an object:

```javascript
var myData = {
  "first_name": "Habdul",
  "last_name": "Hazeez",
  "field" : "Computer science"
};
```

When executed in the console:

![JavaScript object](https://thepracticaldev.s3.amazonaws.com/i/yrmm3q4mpdkpdoropn3f.PNG)

Next, we use `for/in` loop to traverse the property names.

```javascript
/**
  * The for/in loop is used to traverse
  * property names of an object
  */
for (var propertyNames in myData) {
  console.log(propertyNames);
}
```

When executed in the console:

![JavaScript for/in loop](https://thepracticaldev.s3.amazonaws.com/i/mg30t0t2pmtq35clrtdu.PNG)

<hr>

Another looping method was introduced in ES6 called the `for/of` loop.

The `for/of` loop is used to traverse _iterables_ in JavaScript. An example of iterables is an array.

The syntax is:

```javascript
for (var variable  of iterable) {
  // statement
}
```

An example:

```javascript
// Create an array
var myArray = [1, 2, 3, 4, 5, 6];
```

Then we use the `for/of` loop  to traverse the elements:

```javascript
/**
  * The for/of loop was introduced in ES6
  * and it is used to traverse iterables. e.g
  * an array.
  * Here the array is a variable called myArray
  */
for (var arrayElements of myArray) {
  console.log(arrayElements);
}
```

When executed in the console:

![JavaScript for in loop](https://thepracticaldev.s3.amazonaws.com/i/05dr9dzsjmkj00mgofu2.PNG)

<hr>

__UPDATE: 30<sup>th</sup> December 2019__

I used `var` in the variable declarations, but you should know that variables declared with `var` are hoisted which can lead to undesirable results and bugs in your code. As a beginner you might not notice this, but it's really important that you are aware of this.

`let` and `const` were added in __ES6__ to help developers avoid this issue. Variables declared with `let` are not hoisted, cannot be re-declared and are only usable from their point of declaration.

Variables declared with `const` cannot be re-assigned. Any attempt to reassign a variable declared with `const` would lead to a `TypeError`.

Please read this article &rarr; [Quick Tip: Use let with for Loops in JavaScript](https://wesbos.com/for-of-es6/).

All thanks to:

{% user rolandcsibrei %}

<hr>

That's it for now. I'll encourage you to do further experiments to get a good understanding of this entire concepts of loops.

Up next, _functions_. I'll see you then.