JavaScript for of loop

JavaScript for of loop execute block of code for each element iteration of an object (array, sets, and maps).

Syntax

for (var variable of DataExpression)  {
  statements
}

Arguments

  1. variable: Required, A unique variable name (object property) as a reference for assignment every iteration.
  2. objectExpression: Optional, An array, sets or maps, that are iterate and return a result of evaluating the Expression.
  3. statements: Optional, Specified number of statements to be executed in every iteration.

Example (Array)

<script>
  var arr = ['a','b','c'];
  for (var val of arr) {
      console.log(val);        // result "a", "b", "c"
  }
</script>

Run it...   »

Example (Sets)

<script>
  var set = Set([10, 20, 30, 40, 50]);
  for (var val of set) {
      console.log(val);        // result 10, 20, 30, 40, 50
  }
</script>

Run it...   »

Example (Maps)

<script>
  var m = new Map();
  var key1 = 'a';
  var key2 = 'b';
  var key3 = 'c';
  m.set(key1, 'AAA');
  m.set(key2, 'BBB');
  m.set(key3, 'CCC');

  for (var [key, value] of m) {
      console.log(key + " : " + value);
  }
</script>

Run it...   »

Different between for..in and for..of loop in JavaScript.

for...in loop iterate over property keys while
for...of loop iterate over property values.

Example

<script>
  var arr = ['a', 'b', 'c'];
  Array.prototype.d = true;   // prototype to inherit array element

  for (var a in arr){
      console.log(a);           // returns "1", "2", "3", "d"
  }

  for (var a of arr){
      console.log(a);           // returns a, b, c
  }
</script>

Run it...   »