This works just fine, but did you know that Array.prototype (the base array object) contains a number of functions that make performing common tasks based on array iteration more concise?
One such function is map, and map is used to transform an array based on a transformation function. Let’s look at an example using a for loop, then I’ll show you the same thing using map, and I’m sure you’ll agree it’s nicer.
Let’s say we want to transform all the strings in an array to uppercase. Using a for loop we could do:
The same code when using map would be:
As you can see, map makes things much more concise. It removes all of the iteration logic, so you can focus on the transformation you want to perform. As you can see this means less code is required for the same result.
So let’s break down the map function.
It takes as it’s argument an iterator function. That function will be called for each element in the array in turn. The iterator function should return the result of transforming the current array element in some way (uppercasing it in our example).
The return value of map will then be a new array, with every element of the original array transformed by the iterator function. Note that the original array map is called on will not be modified. The transformed elements end up in a new array. It is what we call a pure function.
I’ve only used one argument for the iterator function, the current element in the array for this iteration, but the iterator can take up to 3 arguments:
- element: The current element in the array
- i: The current numerical index of the array
- array: The entire array map was called on (list in our example)
Map is simple. Use it next time you want to transform an array. Give it a go and you’ll never go back to using loops to do this, I promise.