Difference between for-in and for-of in JavaScript?

Difference between for-in and for-of in JavaScript?

for-in
The for-in loop iterates over all the enumerable properties of an object. In each iteration the name of the property is stored in the variable.

Syntax:
for (variable in object)
    statement;

Example:
var obj = {x: 5, y: ‘abc’, z: true};
for (var prop in obj) {
    console.log(prop + ” = ” + obj[prop]);
}

for-of
The for-of iterates over iterable objects (arrays, maps, sets and others).


Syntax:
for (variable of object)
    statement;

In relation to the for-in loop, the for-of loop is a more convenient and iterates over property values.

Example:
var elements = [‘a’, ‘b’, 5, 6];
for (var element of elements) {
console.log(element);
}

Output:
//a
//b
//5
//6

Leave a Reply