Loop : for in & for of

for ...in loop

  • Can only access 'key' of an object

  • Repeat all iterable properties of an object

      var obj = {
          "a": 1,
          "b": 2,
          "c": 3
      }
    
      for (var prop in obj) {
          console.log(`${prop}: ${obj[prop]}`)
          // a: 1
          // b: 2
          // c: 3
      }
    

for ...of loop

  • ES6

  • Whole collection needs [Symbol.iterator] property

      // example 1
      var obj = {
          "a": 1,
          "b": 2,
          "c": 3
      }
    
      for (var key of Object.keys(obj) {
          console.log(`${key}: ${obj[key]}`)
          // a: 1
          // b: 2
          // c: 3
      }
    
      // exampe 2
      var iterable = [10, 20, 30];
    
      for (var value of iterable) {
          console.log(value);
          // 10
          // 20
          // 30
      }