DEV Community

Habdul Hazeez
Habdul Hazeez

Posted on • Edited on

JavaScript Loops

When we talked about conditional statements 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 Firefox 71.0 and its Developer Tools. One particular feature in Firefox 71.0 that's worthy of mention is the multi-line code editor in the console.


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:

while (expression) {
  // statement
}
Enter fullscreen mode Exit fullscreen mode

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.

/**
  * 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++;

}
Enter fullscreen mode Exit fullscreen mode

When executed in the console:

A while loop in JavaScript

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:

do {
  // statement
} while (expression);
Enter fullscreen mode Exit fullscreen mode

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.

/**
  * 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);
Enter fullscreen mode Exit fullscreen mode

When executed in the console:

JavaScript do while loop

for

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

  • a counter a variable — var counter = 0;
  • a conditional test — counter < 10
  • an increment — 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:

for (initialize; test; increment) {
  // statement
}
Enter fullscreen mode Exit fullscreen mode

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

/**
  * 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);
}
Enter fullscreen mode Exit fullscreen mode

When executed in the console:

JavaScript for loop

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:

for (variable in object) {
  //  statement
}
Enter fullscreen mode Exit fullscreen mode

Time for some code. First we create an object:

var myData = {
  "first_name": "Habdul",
  "last_name": "Hazeez",
  "field" : "Computer science"
};
Enter fullscreen mode Exit fullscreen mode

When executed in the console:

JavaScript object

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

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

When executed in the console:

JavaScript for/in loop


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:

for (var variable  of iterable) {
  // statement
}
Enter fullscreen mode Exit fullscreen mode

An example:

// Create an array
var myArray = [1, 2, 3, 4, 5, 6];
Enter fullscreen mode Exit fullscreen mode

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

/**
  * 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);
}
Enter fullscreen mode Exit fullscreen mode

When executed in the console:

JavaScript for in loop


UPDATE: 30th 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 → Quick Tip: Use let with for Loops in JavaScript.

All thanks to:


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.

Top comments (2)

Collapse
 
rolandcsibrei profile image
Roland Csibrei • Edited

Hi Habdul! Thank you for the article, for your effort, BUT, everyone, please check this:

wesbos.com/for-of-es6/

And please, wherever it is possible, stop using var. Guys, it is really time to switch to let and const.

Have a nice day!

Collapse
 
ziizium profile image
Habdul Hazeez

Hi Habdul! Thank you for the article, for your effort, ..

Thank you very much. It means a lot.

And please, wherever it is possible, stop using var. Guys, it is really time to switch to let and const.

This post is aimed at beginners that's why i used var and moreover i was working in the console and multiple declarations with var won't cause an issue but with let and const I'll get lot of errors.

Moreover, i would like anyone learning JavaScript to know where it's been, it's current state and its possible future. If any beginner come across this post and this comments they'll probably research into this topic of not using var and who knows what they might find?

In addition, thank you for the link, i will update the article.