What is the difference between ( for… in ) and ( for… of ) statements in JavaScript?

前端 未结 14 1301
慢半拍i
慢半拍i 2020-11-22 06:22

I know what is for... in loop (it iterates over key), but heard the first time about for... of (it iterates over value).

I am confused with

14条回答
  •  长情又很酷
    2020-11-22 06:25

    There are some already defined data types which allows us to iterate over them easily e.g Array, Map, String Objects

    Normal for in iterates over the iterator and in response provides us with the keys that are in the order of insertion as shown in below example.

      const numbers = [1,2,3,4,5];
       for(let number in number) {
         console.log(number);
       }
    
       // result: 0, 1, 2, 3, 4
    

    Now if we try same with for of, then in response it provides us with the values not the keys. e.g

      const numbers = [1,2,3,4,5];
       for(let numbers of numbers) {
        console.log(number);
      }
    
      // result: 1, 2, 3, 4, 5
    

    So looking at both of the iterators we can easily differentiate the difference between both of them.

    Note:- For of only works with the Symbol.iterator

    So if we try to iterate over normal object, then it will give us an error e.g-

    const Room = {
       area: 1000,
       height: 7,
       floor: 2
     }
    
    for(let prop in Room) {
     console.log(prop);
     } 
    
    // Result area, height, floor
    
    for(let prop of Room) {
      console.log(prop);
     } 
    

    Room is not iterable

    Now for iterating over we need to define an ES6 Symbol.iterator e.g

      const Room= {
        area: 1000, height: 7, floor: 2,
       [Symbol.iterator]: function* (){
        yield this.area;
        yield this.height;
        yield this.floors;
      }
    }
    
    
    for(let prop of Room) {
      console.log(prop);
     } 
    
    //Result 1000, 7, 2
    

    This is the difference between For in and For of. Hope that it might clear the difference.

提交回复
热议问题