-1

I was expecting 1,2,3,4 form using the forEach on the array arr with the condition, but got 1,2,3. Why is this so? Doing a regular forEach on the array without the condition gives the expected output: 1,2,3,4

let arr = [1, 2, 3, 4];
arr.forEach(function(i, x, y) {
  if (i in y) {
    document.write(i);
  }
});
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Don Cheeto
  • 111
  • 1
  • 9
  • 1
    Because `in` refers to *index*. `4` is not one of the indexes in your array. – Tyler Roper Aug 14 '19 at 02:32
  • Not sure who downvoted, but I thought the same thing. It is used as a membership operator, but different implementation details. If I ran the same code in python, the result will be different – Don Cheeto Aug 14 '19 at 03:19
  • Javascript's `in` does not check if that VALUE exists in the array. It checks if that property exists on the object. In general, one would never use `in` with arrays. You can see [Using `in` with HTMLCollection object](https://stackoverflow.com/questions/22754315/for-loop-for-htmlcollection-elements/22754453#22754453) and [for/in loop outputs indices, not values](https://stackoverflow.com/questions/7480020/for-in-loop-with-string-array-outputs-indices/7480175#7480175) for more explanation. – jfriend00 Aug 14 '19 at 05:28

1 Answers1

0

Because in is based on index, not the value. Since index starts at 0, 4 is one greater than the max.

let arr = [0, 1, 2, 3];
arr.forEach(function(i, x, y) {
  if (i in y) {
    document.write(i);
  }
});
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • I'm coming from python and I just checked JS documentation. 'in' is used as a membership operator. ie: is 'value' in 'object'. Do you mean when I used in it was actually pulling the index of the array items and not the items themselves ? – Don Cheeto Aug 14 '19 at 03:17