Computer >> Computer tutorials >  >> Programming >> Javascript

What is the difference between for...in and for...of loops in JavaScript?


Difference between for...in and for...of loops

Both the loops iterate over something. The main difference between them is in what they iterate over.

1) for...in loop

This loop iterates over enumerable properties of an object in an arbitrary order. It cares only about properties but not values.

In the following example by using for...in loop the properties of the array are iterated. Since it is an array, Index is an important property so index of each and every element will be iterated and displayed in the output. In addition to indexes some inherited properties such as "inherProp2", "inherProp1" are also displayed.

Example-1

<html>
<body>
<script>
   Object.prototype.inherProp1 = function() {};
   Array.prototype.inherProp2= function() {};
   var org = ["Apple", "Microsoft", "Tesla"]
   org.anotherOrg = "solarCity";
   for (var key in org) {
      document.write(key);
      document.write("</br>");
}
</script>
</body>
</html>

Output

0
1
2
anotherOrg  // own property
inherProp2 // inherited property
inherProp1 // inherited property


In the following example, since hasOwnProperty() is used, only own properties such as indexes and other properties are displayed where as inherited properties such as "inherProp1" and "inherProp2" are not displayed. 

Example-2

<html>
<body>
<script>
   Object.prototype.objCustom = function() {};
   Array.prototype.arrCustom = function() {};
   var org = ["Apple", "Microsoft", "Tesla"]
   org.anotherOrg = "solarCity";
   for (var i in org) {
      if (org.hasOwnProperty(i)) {
         document.write(i);
         document.write("</br>");
      }
   }
</script>
</body>
</html>

Output

0
1
2
anotherOrg

2) For...of loop

Unlike for...in loop, for...of loop iterates over values that the object defines to be iterated over.

In the following example the properties such as 'Apple', 'Microsoft' and 'Tesla' are displayed in the output using for...of loop.

Example

<html>
<body>
<script>
   var org = ["Apple", "Microsoft", "Tesla"]
   for (var key of org) {
   document.write(key);
   document.write("</br>");
}
</script>
</body>
</html>

Output

Apple
Microsoft
Tesla