Introduction to Javascript loops

Nowadays Javascript can be easily defined as the world most used programming language: it is used on a variety of platforms, it is integrated in web browsers and thanks to the Node.js runtime it can also be used server-side. In this tutorial we will see the loops we can be used in modern Javascript.

In this tutorial you will learn:

  • What is the syntax and how the while loop works in Javascript
  • The syntax of the do/while loop and how it works in Javascript
  • The syntax of the for loop and how it works in Javascript
  • The syntax of the for/of loop and how it works in Javascript
  • The syntax of the for/in loop and how it works in Javascript

Introduction to Javascript loops

Introduction to Javascript loops

Software requirements and conventions used

Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Distribution-independent
Software Node.js to use Javascript outside of web browsers
Other Basic knowledge of Javascript and Object Oriented Programming
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

The while loop

The while loop in Javascript works just as you might expect and you are used to in other programming languages. Its syntax is the following:

while (condition)
  statement

The loop body is executed as long as the condition, checked at each iteration, evaluates to true. Here is an example of the while loop in action:

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

During the loop execution, we obtain the following output:

0
1
2
3
4

In the end, the value of the counter variable will be 5:

> counter
5


The do/while loop

The do/while loop syntax is the following:

do
  statement
while (condition)

It works similarly to the while loop we just saw, with just one difference. Let’s demonstrate it with an example:

let counter = 5;

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

Let’s check the value of the counter variable after the loop is executed:

> counter
6

Initially, we assigned a value of 5 to the counter variable. Even if the test condition of the loop evaluates to false (counter < 5), the value of the counter variable is incremented of 1, so in the end it is 6. That is because, in a do/while loop, the loop body is always executed at least once and than repeated as long as the condition evaluates to true.

The for loop

The for loop is the classical, c-style loop:

for ([initialization]; [condition]; [final-expression])
  statement

The initialization consists, typically, in a variable declaration, evaluated once before the loop is executed. The condition is tested before each iteration of the loop; if it evaluates to true the statement is executed. The final-expression expression, instead, is evaluated at the end of each iteration of the loop. The three blocks are optional, and each one of them can be omitted; however, a typical usage of the for loop is the following:

for (let i=0; i < 5; i++) {
  console.log(i)
}

We used the let keyword to initialize the i variable with a value of 0, then we set the condition, so that the loop statement is executed as long as the value of the i variable is less than 5. Finally, we set the final-expression so that the value of the i variable is incremented of one after each loop iteration. If we execute the code above, we obtain the following result:

0
1
2
3
4

The for/of loop

The for/of loop has been introduced in Javascript with ES6. This kind of loop can be used on iterable objects, such as arrays (or array-like objects such as NodeList), strings, Map, Set. etc. Its syntax is the following:

for (variable of iterable) {
  statement
}

Supposing we have the following array:

const my_array = ['Bruce', 'John', 'Marta'];

We can iterate over it using the for/of loop very easily:

for (let i of my_array) {
  console.log(i);
}

The code above will give us the following results:

Bruce
John
Marta

As stated above, the for/of loop can also be used on strings:

const site = "linuxconfig.org";
for (const c of site) {
  console.log(c);
}

The loop will iterate over each character of the string, giving use the following result:

l
i
n
u
x
c
o
n
f
i
g
.
o
r
g


The for/of loop works also on Map and Set objects. A Map object can be described like a sort of array where arbitrary values can be used as keys instead of just integers. To define a Map Object we can use the Map class constructor, and optionally pass an array containing itself two-elements arrays:

const my_map = new Map([
  ['Name', 'Frodo'],
  ['Race', 'Hobbit']
]);

To iterate over the Map object we just created using the for/of loop, we would write:

for (const name_value_pair of my_map) {
  console.log(name_value_pair);
}

We would obtain:

[ 'Name', 'Frodo' ]
[ 'Race', 'Hobbit' ]

A Set object can also be saw as a sort of a variant of an array. The difference between as Set object and an array is that the former is not indexed and not ordered, and it cannot contain duplicate values. To define a Set object, we use the Set class constructor:

const my_set = new Set(['Frodo', 1]);

To iterate over the Set, we write:

for (const element of my_set) {
  console.log(element);
}

As you could expect we would obtain the following result:

Frodo
1

The for/of loop cannot be used on non-iterable objects, such as “regular” objects. What we can do, is to iterate over the array of the object keys or the array of the corresponding values. To obtain an array with all the keys of an objects we can use the Object.keys method, passing our object as argument. Suppose we have the following object:

let character = {
  name: 'Frodo',
  race: 'Hobbit'
}

If we try to use the for/of loop on it we obtain an error:

for (const j of character) {
  console.log(j);
}
Uncaught TypeError: character is not iterable

We could write the following code to iterate over its keys using the for/of loop:

for (const key of Object.keys(character)) {
  console.log(`${key} is: ${character[key]}`);
}

We would obtain the following result:

name is: Frodo
race is: Hobbit

Iterating directly over the object values it’s just as easy: we can use the Object.values method to obtain an array which contains all the values associated with the object keys:

for (const i of Object.values(character)) {
  console.log(i);
}

As you might expect, the output is:

Frodo
Hobbit

The for/in loop

The for/in loop in Javascript iterates over all the enumerable properties of an object using an arbitrary order. It works on the properties represented by strings, so it will skip Symbols. The loop syntax is the following:

for (variable in object)
  statement


When used on arrays it will iterate over indexes, so for example, iterating over the my_array array we defined before:

for (const key in my_array) {
  console.log(key);
}

will produce the following results:

0
1
2

Here is how, using the for/in loop, we can re-write the code we used before to iterate over the non-iterable character object properties:

for (const key in character) {
  console.log(`${key} is: ${character[key]}`);
}

Conclusions

In this article we saw what are the 5 type of loops we can use in modern Javascript, starting from the while and the do/while loops, and proceeding to examine the for, for/of and for/in loops and their syntax. If you are interested in Javascript as a topic, you can take a look at our articles about arrow functions or higher order functions.



Comments and Discussions
Linux Forum