To start with, what is the first thing we learn about .forEach()
? Stumped? Okay, the first thing we learn is that .forEach()
has no return value so assigning it is pointless since it will just be, undefined
.
Now, as the callback parameters go, the element, what I call x
is just that, the current element of the array. .forEach()
is breakless so will iterate the entire array from left to right, by element. i
is the index of the current element in the iteration. We can use this to enumerate an array:
const arr = ['zero', 'one', 'two', 'three', 'four', 'five']
const obj = {}
arr.forEach((x, i) => obj[i] = x)
console.log(obj)
{
"0": "zero",
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"i": "five"
}
That last value is an unexplained artefact that will take some research to discover why it is there at all. Obviously this needs to be thought out more. You get the idea, though.
Let’s see if we can enumerate the array itself:
arr.forEach((x, i, a) => a[i] = [i, x])
console.log(arr)
[
[0, 'zero'],
[1, 'one'],
[2, 'two'],
[3, 'three'],
[4, 'four'],
[5, 'five']
]
Now we can see where that third optional parameter fits in. It is the array, itself which allows us to work directly on it within the callback.