For the sake of demonstration, suppose you need to generate an array of numbers from 0 to 99. How might you do this?
Here’s one option:
Maybe you haven’t yet drunk the functional programming Kool-aid and you’re thinking the above solution seems perfectly fine. It technically is, but after you’ve had a taste of the magic of higher-order functions, you’re probably thinking, “There must be a better way.”
Perfect, right? I have an array of length 100, so now I just need to map the index to each element.
What the heck!? The first element of the array should be 0, but it’s actually undefined!
is essentially equivalent to this object:
When you access the element at index 0 in an array, you’re really just accessing an object property whose key is 0. This is important because when you think of arrays as objects in conjunction with the way these higher-order functions are implemented (don’t worry, I did that part for you), the cause of our problem makes perfect sense.
When you create a new array with the Array constructor, it creates a new array object with its length property set to the value you passed in, but otherwise the object is a vacuum. There are no index keys in the object representation of the array whatsoever.
It just so happens that the higher-order functions map, reduce, filter, and forEach iterate over the index keys of the array object from 0 to length, but the callback is only executed if the key exists on the object. This explains why our callback is never called and nothing happens when we call the map function on the array — there are no index keys!
As you now know, what we need is an array whose internal object representation contains a key for each number from 0 to length. The best way to do this is to spread the array out into an empty array.
Spreading the array into an empty array results in an array that’s filled with undefined at each index.
Happy coding! 👍