Why Array(n) is Not Iterable in JavaScript
Introduction
If you have come across the use case of iterating n
number of times in JavaScript, chances are, you might have tried to implement the solution below (especially in react, when you need to render a JSX element n number of times).
Array(5).map(() => console.log("hello"))
If you think the above code might print “hello” 5 times, that's not the case. It is not going to print anything! Let’s look at why is that.
Sparse Arrays
When JavaScript arrays are instantiated without any elements but just with the length, elements at all the indices are filled with empty items
.
These elements are not iterable with some array iteration methods like forEach
, map
, filter
, etc. These elements will skip the empty elements and just iterate over other non-empty elements if any.
For example,
const arr = Array(5);
console.log(arr); // [ <5 empty items> ]
arr[1] = 1;
arr[3] = 3;
arr[5] = 5;
console.log(arr); // [ <1 empty item>, 1, <1 empty item>, 3, <1 empty item>, 5 ]
arr.forEach((ele) => console.log(ele)); // 1, 3, 5
If the length of an array is increased by setting the length
property directly or by assigning to an index that is greater than the array’s current length, the new elements would be assigned by empty items
.
const arr = [1, 2, 3];
arr.length = 5;
console.log(arr); // [ 1, 2, 3, <2 empty items> ]
arr[7] = 8;
console.log(arr); // [ 1, 2, 3, <4 empty items>, 8 ]
arr.forEach((ele) => console.log(ele)); // 1, 2, 3, 8
delete arr[1];
console.log(arr); // [ 1, <1 empty item>, 3, <4 empty items>, 8 ]
const newArr = [1, , 2, , 3];
console.log(newArr); // [ 1, <1 empty item>, 2, <1 empty item>, 3 ]
Empty items to undefined
Empty items are treated as undefined
in some operations like for...of
loop, accessing via index, and the spread ...
operator.
const arr = [1, , 2, , 3];
for (const ele of arr) { // 1, undefined, 2, undefined, 3, undefined
console.log(ele);
}
console.log(...arr); // 1, undefined, 2, undefined, 3, undefined
console.log(arr[0]); // 1
console.log(arr[1]); // undefined
Let’s come back to our original problem. The alternatives that can be used for looping n
number of times in a single statement.
[...Array(3)].map((e) => console.log(e)); // undefined, undefined, undefined
Array.from({ length: 3 }).map((e) => console.log(e)); // undefined, undefined, undefined
Conclusion
The above methods come in handy when you need to iterate for a certain number of times in a single statement, like rendering a JSX element multiple times in React.
That’s all folks! Thanks for reading.