I like Array.forEach()
and use it whenever I need to iterate through elements. However one needs to be aware of its quirk.
1
2
3
|
const arr = new Array(5);
arr[0] = 0;
arr[4] = 4;
|
A typical for
outputs all elements including those not initialized yet (hold your breath for a moment on the initialized thing).
1
2
3
4
5
6
7
8
|
for (let i = 0; i < arr.length; i++) console.log("for rocks", arr[i]);
/* output
for rocks 0
for rocks undefined
for rocks undefined
for rocks undefined
for rocks 4
*/
|
Now, repeat the same for forEach
.
1
2
3
4
5
6
|
arr.forEach(ele => console.log("forEach rocks too"));
/* output
forEach rocks too
forEach rocks too
*/
|
Hmm.. that is strange.
Let’s use a fill
with array but not assign any value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
const arr = new Array(5).fill();
arr[0] = 0;
arr[4] = 4;
for (let i = 0; i < arr.length; i++) console.log("for rocks", arr[i]);
arr.forEach(ele => console.log("forEach rocks too"));
/*
for rocks 0
for rocks undefined
for rocks undefined
for rocks undefined
for rocks 4
forEach rocks too
forEach rocks too
forEach rocks too
forEach rocks too
forEach rocks too
*/
|
What is this black magic?
I am flabbergasted. Is forEach
right for me?
Yes.
forEach
is pretty, smart and committed (to the future of Javascript). You can both live a happy life.
A better question to think about is why we initialize empty arrays like crazy.