JavaScript for of Loop
JavaScript for of loop execute block of code for each element iteration of an object (array, sets, and maps).
JavaScript for of Loop
Syntax
for (var variable of DataExpression) {
statements
}
Arguments
- variable: Required, A unique variable name (object property) as a reference for assignment every iteration.
- objectExpression: Optional, An array, sets or maps, that are iterate and return a result of evaluating the Expression.
- 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>
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>
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>
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>