24

I am just wondering why it is not possible to make forEach on array of undefined.

Code:

var arr = new Array(5); // [undefined x 5]

//ES5 forEach
arr.forEach(function(elem, index, array) {
    console.log(index);
});

//underscore each
_.each(arr, function(elem, index, array) {
    console.log(index);
});

Both examples do not execute function.

Now to make foreach, I have to make:

var arr = [0,0,0,0,0];

Then make forEach on it.

I am trying to make an array with specified size and loop through it, avoiding for loop. I think that it is clearer using forEach than for loop. With array with length 5 it is not a problem, but it would be ugly with bigger arrays.

Why there is a problem looping through array of undefined values ?

Tukkan
  • 1,574
  • 2
  • 18
  • 33
  • 3
    Because `Array(5)` isn't an Array of `undefined`. It has exactly `0` members even though its `.length` has been pre-defined. – cookie monster May 04 '14 at 19:03
  • 1
    ...though I'm not sure what you're expecting when you say the examples "return `undefined`". The `.forEach()` method will always return `undefined`, no matter what it iterates over. The question seems like it should be whether or not the callback is invoked. – cookie monster May 04 '14 at 19:06
  • You're right, not return undefined, but do not execute function. – Tukkan May 04 '14 at 19:10
  • What about `var arr = [1, undefined, 2]` and then `forEach` ? It works on that array and function executes 3 times. Same with `[undefined, undefined]`. Seems that `undefined` created by array constructor and created literally are different :) – Tukkan May 04 '14 at 19:10
  • 1
    `Array(5)` is essentialy equivalent to `var arr = []; arr.length = 5`. Which means changing array's length doesn't set any values for it's numeric properties (numeric properties are undefined instead of having undefined values) – soulcheck May 04 '14 at 19:19
  • @Tukkan: That one is because you explicitly defined `arr` to have its second member set to the `undefined` value, so the member does exist. Now do it like this `var arr = [1, , 2]`. You'll find that the second member is passed over. This is because JS Arrays can be sparse, and when `forEach()` iterates, it does an `in` test to see if the member exists, and if not, it passes over that member instead of invoking the callback. – cookie monster May 04 '14 at 19:32
  • 2
    ...if you want a quick solution, you can do this: `var arr = Array.apply(null, Array(5))`. It's a little longer, but not too bad. Or just create a separate function that does it for you. `function A(n) { return Array.apply(null, Array(n)); }` `var arr = A(5);` – cookie monster May 04 '14 at 19:54
  • Possible duplicate of [JavaScript "new Array(n)" and "Array.prototype.map" weirdness](https://stackoverflow.com/questions/5501581/javascript-new-arrayn-and-array-prototype-map-weirdness) – KyleMit Mar 28 '19 at 20:10

5 Answers5

31

Array(5) is essentialy equivalent to

var arr = []; 
arr.length = 5;

In javascript changing array's length doesn't set any values for it's numeric properties nor does it define those properties in the array object. So numeric properties are undefined instead of having undefined value. You can check it by using:

Object.keys(arr)

When iterating javascript iterates through numeric properties of the array, so if these don't exist, there is nothing to iterate over.

You can check it by doing:

var arr = Array(5)

//prints nothing
arr.forEach(function(elem, index, array) {
    console.log(index);
});

arr[3] = 'hey'
//prints only 'hey' even though arr.length === 5
arr.forEach(function(elem, index, array) {
    console.log(index);
});

The following code:

var arr = [undefined, undefined];

creates and array of length ===2 and sets the both numeric properties 0 and 1 to undefined.

soulcheck
  • 36,297
  • 6
  • 91
  • 90
6

Looking at a simplified implementation of .forEach() may help.

Array.prototype.my_for_each = function(callback, thisArg) {
    for (var i = 0; i < this.length; i++) {
        if (i in this) {
            callback.call(thisArg, this[i], i, this);
        }
    }
};

So you can see that what happens is that the method does iterate the entire Array (according to the spec), but it only invokes the callback if the member actually exists. It checks by looking for the property (the index) using the in operator, which tests to see if the object either has or inherits the property.

If in shows that the index exists, the callback is invoked.


So given this Array:

var arr = ["foo", "bar", "baz"];

This will output all 3 items:

arr.my_for_each(function(item) {
    console.log(item);
});
// "foo" "bar" "baz"

But if we use delete to remove a member, it leaves a hole in the Array, which will now get passed over.

delete arr[1];

arr.my_for_each(function(item) {
    console.log(item);
});
// "foo" "baz"

When you created an Array using Array(5), it created one without any members, but with the .length set to 5. So this is an example of a sparse Array (very sparse in this instance). Because none of the indices will be found by in, the callback is never invoked.

cookie monster
  • 10,671
  • 4
  • 31
  • 45
3

You can use Array.from to create an array and pass lambda function that will be invoked on each item in the array. detailed documentation

  const arr = Array.from(
      { length: 5 },
      () => 0
  )

  console.log(arr)
Alexander Kondaurov
  • 3,677
  • 5
  • 42
  • 64
2

Other answers have explained the problem, but not provided solutions.

ES6 Spread syntax fills in sparse values with undefined. So does Array.apply(null, sparseArray), which has the benefit of working in older browsers, but takes a bit more work to understand.

const sparseArray = new Array(5);
const unsparseArray1 = Array.apply(null, sparseArray);
const unsparseArray2 = [...sparseArray];

function arrayApply() {
  // ES5 forEach works with either approach
  unsparseArray1.forEach(function(elem, index, array) {
    console.log(index);
  });
}

function es6Spread() {
  // Lodash each works with either approach
  _.each(unsparseArray2, function(elem, index, array) {
    console.log(index);
  });
}
<html><head>
  <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
  <title>Making sparse arrays unsparse</title>
</head><body>
  <p><button onclick="arrayApply();">Array.apply(null, sparseArray)</button></p>
  <p><button onclick="es6Spread();">[...sparseArray]</button></p>
</body>
</html>
Clement Cherlin
  • 387
  • 6
  • 13
0

In my case, I was looking for an elegant solution to creating an array of digits starting with 0 to X.

In an elegant manner with arrow functions, it comes up with a 1 line of code

const arrayLength = 10;
const arrayOfDigits = Array.apply(null, Array(arrayLength)).map((_, index) => index);

Appeared to me quite a sophisticated one, much more than a separate block of code with a for cycle.