Search code examples
javascriptloopsforeachenumerationfor-in-loop

What is the difference between for..in and for each..in in javascript?


What is the difference between for..in and for each..in statements in javascript? Are there subtle difference that I don't know of or is it the same and every browser has a different name for it?


Solution

  • "for each...in" iterates a specified variable over all values of the specified object's properties.

    Example:

    var sum = 0;
    var obj = {prop1: 5, prop2: 13, prop3: 8};
    for each (var item in obj) {
      sum += item;
    }
    print(sum); // prints "26", which is 5+13+8
    

    Source

    "for...in" iterates a specified variable over all properties of an object, in arbitrary order.

    Example:

    function show_props(obj, objName) {
       var result = "";
       for (var i in obj) {
          result += objName + "." + i + " = " + obj[i] + "\n";
       }
       return result;
    }
    

    Source


    Note 03.2013, for each... in loops are deprecated. The 'new' syntax recommended by MDN is for... of.