This post was written to remind me how, why and when to use the .map method.
map()method creates a new array populated with the results of calling a provided function on every element in the calling array.”
Why and When:
When you want to make the same changes to all the elements in an array. An example of this could be when a monetary value is stored in an array, in it’s lowest unit, and it needs to be converted into a higher unit. i.e pence to pounds.
In the below example, the currency needs converting from euros to dollars
A variable called energyCostDollars was assigned to the current array. The current array variable has the .map method added to the end of it. Within the .map(), the function word is placed with a further parameter. Within this further parameter, you should use a descriptive word that relates to the element you are changing. (As this word represents the elements in the originally array – i sort of visualize this as the counter in the for loop. I’m not sure if this is good practice though). Finally, the return keyword is used and the descriptive word you used in the function parameter is returned with whatever action you want to happen. In the above case it is multiplying by the exchange rate value.
Please note this is definitely not 100% accurate and it’s my interpretation to try and grasp the concept of the .map method.