What is the difference between the for ... of and the for..in?

17

I was checking out this SOEN question and there I saw this for..of .

I've never seen this before in Javascript .

This is a new feature and we can already implement it reliably, or should we still use the old for..in ?

What's the difference between it and for..in ?

    
asked by anonymous 02.10.2015 / 17:58

3 answers

14

for..of is a building new in EcmaScript 6, so it should only be used when browsers supports this version appropriately, and enables it by default. Otherwise, your code may be rejected by a significant portion of your users.

for..of is similar to for..in , except that it only iterates over properties enumerable of the object / array. A for..in iterates over all of them, including custom properties added by the user:

function log(x) { document.body.innerHTML += "<pre>" + x + "<pre>"; }

var arr = [1,2,3];
arr.foo = "bar";

var obj = { 0:1, 1:2, 2:3, length:3, foo:"bar" };

var obj2 = Object.create(null, {
  0: { value:1, enumerable:true },
  1: { value:2, enumerable:true },
  2: { value:3, enumerable:true },
  length: { value:3 },
  foo:{ value:"bar" }
});

document.body.innerHTML += "<h1>for..in</h1>";

for ( var p in arr ) {
  log("arr[" + p + "] = " + arr[p]);
}
for ( var p in obj ) {
  log("obj[" + p + "] = " + obj[p]);
}
for ( var p in obj2 ) {
  log("obj2[" + p + "] = " + obj2[p]);
}
      
document.body.innerHTML += "<h1>for..of (simulação)</h1>";
      
arr.forEach(function(e, i) {
  log("arr[" + i + "] = " + e);
});
arr.forEach.call(obj, function(e, i) {
  log("obj[" + i + "] = " + e);
});
arr.forEach.call(obj2, function(e, i) {
  log("obj2[" + i + "] = " + e);
});

In the example above, I used Array.prototype.forEach to simulate a for..of - since otherwise the example would not compile in all browsers , and according to MDN the behavior of both should be the same. It should also be noted that for..of applies to both arrays and array-likes, so it can be used even in a list of DOM nodes (returned by document.querySelectorAll for example) .

P.S. As pointed out in

02.10.2015 / 18:29
6

Apparently, for .. of creates a loop to interact with iterable objects (Arrays, Sets, Maps) according to MDN , while for .. in interacts with object properties

  

in relation to for ... in, the MDN page describes

     

for ... of - a similar statement that interacts with the values strong> properties

Example

let arr = [3, 5, 7];
arr.foo = "hello";

for (let i in arr) {
   console.log(i); // logs "0", "1", "2", "foo"
}

for (let i of arr) {
   console.log(i); // logs "3", "5", "7"
}

for...in registered indexes of array and property foo

The for...of has registered the values of each of the indexes of array which is an interactable object

    
02.10.2015 / 18:25