How to get everywhere you need to with a JavaScript map

A function that I have learned and used multiple times over the last few weeks is JavaScript's .map() function. This function gives you the ability to apply another function to every single element in an array. It creates a new array, iterates through every element of the array that it is applied to, and fills the new array with the results of the operations on the elements of the old array. This function is specific to arrays, so don't try to use it on anything else!

We can easily demonstrate how it works through an example: Let's pretend that we have a mission to go to different countries around the world and find their capital cities. We can use a map to find our way around. Assume the function findCapitalCity(x) returns the capital of the country known as "x". We'll have an array of countries we need to find the capitals of, then we will call the .map() function to find the capital cities of each country in the code snippet below:

let countries = [Nigeria, Ghana, Togo, France, Scotland, Canada, USA];
const capitals = countries.map(country => findCapitalCity(country));
console.log(capitals);  //This will print the contents of the capitals array to the console

Printed on the console, we will see: [Abuja, Accra, Lomé, Paris, Edinburgh, Ottawa, Washington]. The capital cities of Nigeria, Ghana, Togo, France, Scotland, Canada, and USA respectively.

Thanks for reading! Until next week, Pamilerin