3 minutes read

You already know the basic syntax of the for loop. However, the classic use of the for loop can be inconvenient in some situations. For example, when we want to iterate over the keys or values of an array or object. To do this, in JavaScript we use a more convenient construction. Let's take a closer look at using a for loop with objects.

For ... in syntax

First, let's create an object. For example, this object will contain fields with the characteristics of a book.

let book = {
    name: 'Crime and Punishment',
    author: 'Fedor Mikhailovich Dostoevsky',
    publicationDate: 1866
}

Suppose we want to print all the keys of an object to the console. If we were talking about arrays, using the classic for loop would be our first choice. But here we cannot use this construction, because the keys are not numbered. A wonderful construction for ... in comes to our aid, which iterates over the keys of the object (similarly to arrays).

for (let key in book) {
    console.log(key);
}

We get the following as the output:

name
author
publicationDate

What do you think will happen if we do the same with the book array?

let book = ['Crime and Punishment', 'Fedor Mikhailovich Dostoevsky', 1866];

You probably guessed it, but there will be the following output:

0
1
2

You probably saw the connection between an object and an array. They have common values, but there are different keys.

Non-obvious behavior

We noticed in the previous example that the keys in the object were printed in the console in order. Let's experiment, since we know that there are a lot of weird things in JavaScript. Let's use for ...in for the following object:

let secondBook = {
    "3": 'Doomed city',
    "1": 'Brothers Strugatsky',
    "0": 1972
}

It's important to understand that the word key in the construction under consideration is not special, we can safely use any other notation for our variable. In the example below, the name i is used.

for (let i in secondBook) {
    console.log(secondBook[i]);
}

Note that for a variety of examples, we printed the values of the object this time.

We will see the following in the console:

1972
Brothers Strugatsky
Doomed city

As you can see, the values were displayed in a strange order, because the date was the last in the object, but it was printed first. This is due to converting keys into numerical values and sorting them implicitly. Therefore, it is worth paying attention to such things that might cause bugs in your code.

Conclusion

In this topic, you've learned the use of the for ... in construct for objects and partly for arrays. Also, we've covered what hidden effects can cause bugs in our programs. Hopefully, you've also diversified your arsenal and learned a more compact way to display the keys of different objects.

53 learners liked this piece of theory. 1 didn't like it. What about you?
Report a typo