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