Monday, February 10, 2020

Difference between ( for… in ) and ( for… of ) statements in JavaScript

For… in

for… in loops over enumerable property names of an object, In each iteration, the name of the property is stored in the variable.

Ex:

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

Output

For… of

The for...of loop is used to loop over any type of data that is iterable(arrays, maps, sets, and others).

Ex:

const digits = [0, 1, 2, 3, 4];
for (const digit of digits) {
  console.log(digit);
}

Output

No comments:

Post a Comment