Deep Tech Point
first stop in your tech adventure

For keyword in JavaScript for loop, for/in loop and for/of loop

January 12, 2022 | Javascript

Loops are a beautiful thing – they can cut down lines and lines of your code because loops are used to avoid repeating a block of code. Therefore, if you want to run one code time and time again, but each time with a different value, use a loop. Want to repeat some message 10 times? Use a loop.

JavaScript supports five types of loops:

We’ve already covered while loops in previous articles, but in one, we will focus on the first three loops that contain the for keyword. So, let’s see what these three for loops are all about.

A for loop

As we said at the beginning, a for loop loops through a block of code a certain number of times. It’s syntax looks like this:

for (startingExpression; condition; updatedExpression) {
  // block of code that should be executed
}

A startingExpression executes only once – before the block of code is executed. Usually, we use the startingExpression to start or initialize the variable that is used in the loop. In addition to that, we can initiate as many values as we want, but we have to separate them with commas. As said, initializing the variable in a startingExpression is usually the case, however, the startingExpression is not required – it is optional and we can skip it. An example would be when we set the values before the loop starts. Let’s check what we are talking about through a few examples.

We initialize the variable with the startingExpression

for (let a = 1; a < 10; a++) {
  console.log("The displayed number is " + a);
}

The code above says:

Initiating as many values as we want in the startingExpression

Yes, we can do that, too, but we have to separate them with a comma. Maybe the example below may not look like it makes a lot of sense, but we wanted to show an example where we initiate as many values as we want in the startingExpression.

for (let a = 0, len = fruits.length; a < len; a++) {
  console.log(fruits[a]);
}

For example, we define an array with a list of fruits - let's say orange, apple, pear, pineapple. Afterward, in a startingExpression you can see we've defined we want a list to start with a first array element (a = 0) and we also added a predefined length property of an array, which returns the number of elements in that array, so if we add elements to an array, the number of elements in the array, and consequently the results of our loop get updated, too. The condition for the loop is to have a variable smaller than the number of fruit elements in an array, but since the starting default for arrays is 0, all fruits in the array will be shown in console. The updatedExpression increases the value of an array each time it goes through a loop.

You can avoid the startingExpression if you set the values before the loop starts

The example below will also list all the fruits in the array:

let i = 0;
let len = fruits.length;
for (; i < len; i++) {
  console.log(fruits[i]);
}

What if we skip the condition in the for loop?

Most often, we use the condition in the for loop to evaluate the initial variable. However, we can omit this step and skip the condition in the for loop, but in this case, we must use a break statement inside the loop, because if we don't, we are dealing with a never-ending loop, which will crash your browser.

Can we skip the updatedExpression in the for loop?

Yes, we can even omit the updatedExpression (the part where we in previous examples incremented the value of a variable inside the loop), too.

let i = 0;
let len = fruits.length;
let text = "";
for (; i < len; ) {
  text += fruits[i] + "
"; i++; }

for/in loop

A for/in loop loops through the properties of an object. Let's take a look at the syntax:

for (a key in an object) {
  // block of code that needs to be executed
}

And now, let's take a look at an example and explain what the code is all about. The for/in loop iterates over a fruits object and each iteration returns a key, which is a and is used to access the value of a key, in our case the value of the key is fruits[a], and the for/in statement loops through the properties of an object, in our case banana, yellow and sweet.

const fruits = {name:"banana", color:"yellow", taste:"sweet"};

let text = "";
for (let a in fruits) {
  text += fruits[a];
}

The for/in loop can be used in arrays too

The for in loop can be used to loop over the properties of an array, too. However, do not use that the for/in loop with arrays if the index order is important because the index order is implementation-dependent. Therefore you might not access array values in the order you would expect. If the order of array values is important, you should use a for loop or for/of loop, or Array.forEach().

What about the for/of loop?

The main reason we use the for/of loop is so we can loop through the values of an iterable objects and data structures, such as arrays, strings, maps, sets. typedarray, nodeLists, and user-defined iterables. The syntax of the for/of loop looks like this:

for (variable of iterable data structure) {
  // the block of code to be executed
}

Let's take a look at the for/of loop on an example of an array:

const numbers = [1, 2, 3];

for (const value of numbers) {
  console.log(value);
}
// 10
// 20
// 30

Let't take a look at for/of loop on an example where it iterates through a string:

const stringExample = "string";

for (const letter of stringExample) {
  console.log(letter);
}
// "s"
// "t"
// "r"
// "i"
// "n"
// "g"