SoFunction
Updated on 2025-02-28

Detailed explanation of the difference between for of and for in in JavaScript

First, let’s introduce for of

for of is a new thing added in es6. If for of gives us the most intuitive manifestation is to use for of to traverse the array, the value value is printed directly, which is different from the index value index printed by for in. This is the most intuitive feeling for us beginners.

Secondfor ofThe most essential difference is that it cannot be used to traverse directlyOrdinary object, but can only traverse and deployIterator (iterator)The class array object of the interface.

So what isiteratorWoolen cloth?

Iterator is such a mechanism. It is an interface that provides a unified access mechanism for various different data structures. Any data structure can complete the traversal operation as long as the Iterator interface is deployed (that is, all members of the data structure are processed in turn)

The following example just shows that for of cannot traverse ordinary objects:

let obj2 = { x: 1,y: 2, z: 3,};
for (const value of obj2) {
  (value);
}
//An error occurred while traversing//Uncaught TypeError: obj2 is not iterable

This is because ordinary objects are notIterable object, The iterable object mentioned here is an implementationIterator protocolThe object, where the iterator protocol requires the object to deploy thisiterator, and this method is to mount it under the prototypeSymbol()Method, so when we use for of to process, for example, an array, we actually call this method under the array prototype. Whenever we call this method,The next method will be returned inside the method, which is equivalent to a "pointer". The next time the "pointer" is called, it will move later.

Many students may still feel confused about this. Here is an example to illustrate:

let obj = {
  data: [1, 2, 3],
  // Here is an iterator method for the object  []() {
    let index = 0;
    const data = ;
    return {
      next() {
        if (index < ) {
          return {  value: data[index++], done: false, };
        } else {
          return { done: true };
        }
      },
    };
  },
};
for (const value of obj) {
  (value);
}//1 2 3

After such processing, we implement the iterator method for the object. In this way, we can use for of to traverse this obj object. Everyone will be confused after reading this code, which is mainly correctandnext methodIf I don’t understand, I will briefly introduce these two methods.

  • What is this? In fact, this property is a function, itsThe return value is an iterator object, after we define this property in the object, when we usefor ofWhen the language mechanism will find a way, this method isnext method, When we use this property in an object, we actually override the default iterator, so that we can implement our own logical code.
  • Secondly, we need to pay attention to the iterator object returned: we need to know that the iterator object isObject with next method, and the return value of this next method is alsoMust be an object containing value and done. Where value is the current value, and done indicates whether all traversal is completed.
  • So how is iterator generally used? In fact, whether it is an array, object, collection or other data structure, iterator is provided.next method, Every time I call this next method,Return the next value of this data set, think about the "pointer" movement in C language, which explains why there is a next method here.
  • So this part of the code becomes easier to understand, we have implemented aMethod, then define the index index in it and get the data array. Then we return an iterator object containing iteratornext method, and then make a judgment that if the current index is less than the length of the array, then an object is returned to contain the value value and done at this time, and done is false, indicating that the iteration has not been completed at this time, otherwise it will eventually return a done as true, indicating that the iteration event has been completed at this time.

After the above processing, you can also see that this is very troublesome. What if we don’t want to get each value in this way? Then we can only use some clever means to deal with it:We need to avoid traversing objects directly, but we need to perform a transitional processing through some method.

So if we want to use for of iterate objects, then we can only process and process them through some means.

let sum = 0;
let obj3 = {x: 1,y: 2, z: 3,};
for (const value of (obj3)) {
  sum += value;
}
((obj3));//[1,2,3]
(sum);//6

We used it hereMethods to get the value in the object, and after processing, return an array, which contains the values ​​in the object. Like arrays, Map. Set, string, these are all types with built-in iterator, so you can use for of for to for to for to to. Of course, we can also use methods such as () and () to handle it, so we will not expand it here.

Let's talk about it for in

After introducing for of, let's talk about it immediatelyfor infor inThe most direct manifestation is itYou can directly traverse the data of object type, there is no need to add an iterator property to it like for of. I will introduce it below:

let obj4 = {
  hobby: "Sing, dance, rap",
  name: "kun",
  sex: "male",
};
for (const key in obj4) {
  ("Attribute Name" + key, "Attribute Value" + obj4[key]);
}

In this way, there will be no errors and the output value can be printed normally. So if we use it in the actual scenarioGenerally, for in processing objects must be used to process them., but if you encounter strings, maps, etc., types that have iterators, we can hand them over to for of to handle them.Specific description of the specific scenario.

At the same time, this also proves that the above-mentioned use of for in print the key value, so if we want to obtain the attribute value, we must pass obj4[key].

Similarly, using for in we can also process data like map, set, string and other types. But the most significant difference between for of is that we can directly process objects.

Summarize

Here we explain why for of cannot be used to deal with ordinary objects and how to deal with them. We also introduce the problems that each method is suitable for solving. Therefore, when we use them, we should analyze and process them according to the specific scenario.

This is the end of this article about the detailed explanation of the difference between for of and for in JavaScript. For more information about the differences between for of and for in JavaScript, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!