JavaScript For-in Loop

The JavaScript for...in loop is used to iterate the properties of an object. The basic syntax of For-in loop is :
 for (variable_name in object) {
   block of code to be executed
 }
In each iteration, one property from object is assigned to variable_name and this loop continues till all the properties of the object are exhausted.

The For-in loop example with array :
<!DOCTYPE html>
<html>
<head>
  <title>For Loop</title>
</head>
<body>
  <script>
    brk = "<br/>";
    var fruits = ['apple', 'banana', 'mango', 'graps', 'watermelon', 'lemon'];
    var frt;
    for(frt in fruits) {
      document.write(fruits[frt]);
      document.write(brk);
    }
  </script>
</body>
</html>
Output :


The For-in loop example with object :
<!DOCTYPE html>
<html>
<head>
  <title>For Loop</title>
</head>
<body>
  <script>
    brk = "<br/>";
    var obj = {'name':'Jon snow', 'age':30, 'Occupation':'Warrior','Post Name':'King of North'};
    var frt;
    for(key in obj) {
      document.write(key, ' : ', obj[key]);
      document.write(brk);
    }
  </script>
</body>
</html>
Output :



Next Topic :