Craig Craig -4 years ago 136
Javascript Question

Using a for each loop on an empty array in JavaScript

I've found that I can't use a for each loop on an empty array in javascript. Can anyone explain to me why this is?

I've initialized an array in javascript like so:

var arr = new Array(10);


when I use a for each loop on the array nothing happens:

arr.forEach(function(i) {
i = 0;
});


the result is still an array of undefined values:

arr = [ , , , , , , , , , ];


I think that maybe since each item in the array is undefined, it doesn't even execute the forEach. I would think that it would still iterate through the undefined items. Can anyone explain why this is occurring? This question is not asking how to most efficiently fill an array with zeros, it's asking details on the interaction of a for each loop and an empty array.

Answer Source

You're half-way right!

I think that maybe since each item in the array is undefined, it doesn't even execute the forEach.

Array.prototype.forEach does not visit indices which have been deleted or elided; this is a process called ellision. So, it executes, but skips over every element.

From MDN: Screenshot from MDN regarding forEach

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download