0

When running this code I expect this to log 5 undefined's. However I only see two. It appears that JavaScript only logs undefined's that you define yourself.

var a = [];
a[0]=undefined;
a[4]=undefined;
a.forEach((i)=>console.log(i))

This logs:

undefined
undefined

Wouldn't you expect it to log 4 undefined's?

Here is a codepen.

Johnston
  • 20,196
  • 18
  • 72
  • 121
  • `.forEach` iterates only through values you HAVE in the array. The indeces you do _not_ set to `undefined` are not actually undefined but are empty. Chrome will report them as undefined, though, just to confuse matters. – VLAZ Nov 29 '16 at 22:23
  • `for` loop works as you expected – The Reason Nov 29 '16 at 22:25
  • If you log `a[1]` you get `undefined` – dgo Nov 29 '16 at 22:26

3 Answers3

4

Quoting mdn:

forEach method executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays like your example),

From what I remember the lo-dash forEach method is different it behaves like you would expect.

maioman
  • 18,154
  • 4
  • 36
  • 42
2

It is because of forEach loop.

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).

--Source MDN

Example Snippet:

var a = [];
a[0] = undefined;
a[4] = undefined;
a.forEach(function(i) {
  console.log(i)
})


for (var i = 0; i < a.length; i++) {
  console.log(a[i] + " from for loop");
}
Ajay Narain Mathur
  • 5,326
  • 2
  • 20
  • 32
1

so javascripts arrays are basically just special obejcts that have integer keys (there are some minor differences). so you defined an object with 2 keys values. 0: undefined and 3: undefined. since theres only 2 things in the array, it only prints 2 undefineds.