Search code examples
javascriptfor-in-loop

How does "for in" loop work in Javascript?


The program is as follows,

function sum(x) {
  console.log(typeof x[0]); //return Number
  var s=0;
  for(var e in x) {
    console.log(typeof e); //This return string
    s+=e;
  }
  return s;
}
console.log(sum([1,2,3,4,5])); //return 001234

If I use a number constructor then it works fine.

function sum(x) {
      console.log(typeof x[0]); // return Number
      var s=0;
      for(var e in x) {
        s+=Number(e);
      }
      return s;
    }
    console.log(sum([1,2,3])); //return 6

What is happening at for in loop?


Solution

  • Others have already pointed out that for-in iterates over properties, not values. In the case of an array the properties are the indices.

    function sum(x) {
      var s=0;
      for(var e in x) {
        s+=e;
      }
      return s;
    };
    var array = [1,2,3,4,5];
    array.b="z";
    console.log(sum(array)); // prints 001234b

    In the resulting 001234b string you have: Leading "0": The initial value of s Then "0" because first index is 0 Then "1", etc