What is the difference between ( for... in ) and ( for... of ) statements? What is the difference between ( for... in ) and ( for... of ) statements? arrays arrays

What is the difference between ( for... in ) and ( for... of ) statements?


for in loops over enumerable property names of an object.

for of (new in ES6) does use an object-specific iterator and loops over the values generated by that.

In your example, the array iterator does yield all the values in the array (ignoring non-index properties).


I found a complete answer at Iterators and Generators (Although it is for TypeScript, this is the same for JavaScript too)

Both for..of and for..in statements iterate over lists; the valuesiterated on are different though, for..in returns a list of keys onthe object being iterated, whereas for..of returns a list of valuesof the numeric properties of the object being iterated.

Here is an example that demonstrates this distinction:

let list = [4, 5, 6];for (let i in list) {   console.log(i); // "0", "1", "2",}for (let i of list) {   console.log(i); // "4", "5", "6"}

Another distinction is that for..in operates on any object; it servesas a way to inspect properties on this object. for..of on the otherhand, is mainly interested in values of iterable objects. Built-inobjects like Map and Set implement Symbol.iterator property allowingaccess to stored values.

let pets = new Set(["Cat", "Dog", "Hamster"]);pets["species"] = "mammals";for (let pet in pets) {   console.log(pet); // "species"}for (let pet of pets) {    console.log(pet); // "Cat", "Dog", "Hamster"}


Difference for..in and for..of:

Both for..in and for..of are looping constructs which are used to iterate over data structures. The only difference between them is the entitiesthey iterate over:

  1. for..in iterates over all enumerable property keys of an object
  2. for..of iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.

Example:

let arr = ['el1', 'el2', 'el3'];arr.addedProp = 'arrProp';// elKey are the property keysfor (let elKey in arr) {  console.log(elKey);}// elValue are the property valuesfor (let elValue of arr) {  console.log(elValue)}