0

When I iterate using for loop the output shows 7 undefined indexes but for the same in forEach loop it does not show that. And If I assign "undefined" to any of the indexes, It shows in foreach loop. Why is that? This is the code snippet:

let x = [1, 2, 3];
x[10] = 55; // explicitly passing value to 10th index of array

for (let i = 0; i < x.length; i++) {
  console.log(x[i]);
}

x.forEach((item) => {
  console.log(item);
});

Output:

for loop output:

1
2
3
7 <undefined>
55

forEach loop output:

1
2
3
55
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • `forEach` method will iterate through an array object and will skip all array elements which don't exist at all – Chris G Jan 04 '23 at 13:41
  • @ChrisG no, it's not true. It will skip empty element, but will iterate over `null` and `undefined` – Konrad Jan 04 '23 at 13:41
  • 1
    [`forEach(callbackFn)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach): _"`callbackFn` is invoked only for array indexes which have assigned values. It is **not invoked for empty slots** in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays)."_ – Andreas Jan 04 '23 at 13:43
  • corrected my comment, it actually skips elements which don't exist at all – Chris G Jan 04 '23 at 13:43
  • References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for Now if you run `console.log(Object.keys(x));` before and after the `x[10] = 55;` you can see how the new key was added - keys are non-negative integers. `[ "0", "1", "2", "10" ]` so as you see the array `.forEach` uses the keys but the `for` is not part of the array prototype and does not know about the keys. – Mark Schultheiss Jan 04 '23 at 13:53
  • `push(23)` if done after the `x[10]` would add a new key (11) with value 23 since it mutates the array – Mark Schultheiss Jan 04 '23 at 13:59

0 Answers0