Definitely look at the functional programming section.
map
is an example of a function that takes another function as an argument – called a “higher order function”. What it does is take a collection of things (an array in JS), and applies that function to every one in turn, returning a new collection where all the values in the original collection have been transformed (mapped) by the function. It is I guess a very weird thing when you’re barely familiar with programming. It’s declarative, so rather than writing a loop and doing things in the loop, you just say to the computer “here’s an array, here’s a function. Please run the function on every one of the values in the array, I don’t care how you do it”.
You have an array of numbers, and you want to multiply them all by 2.
numbers is a list of numbers
doubledNumbers is an empty list
for every number in the list of numbers:
put (number × 2) into the doubledNumbers list
So
const numbers = [1, 2, 3, 4, 5, 6];
const doubledNumbers = [];
for (let i = 0; i < numbers.length; i++) {
doubledNumbers.push(numbers[i] * 2);
}
Make that into a function, so that I can use any lost of numbers instead of just the one there:
function doubleNumbers (numbers) {
const doubledNumbers = [];
for (let i = 0; i < numbers.length; i++) {
doubledNumbers.push(numbers[i] * 2);
}
return doubledNumbers
}
Now I can do for example doubleNumbers([10, 20])
and that will give me [20, 40]
back.
I maybe want other things, like sometimes triple numbers, or quadruple numbers. So now, take the .push(numbers[i] * 2)
bit. I could write a function for the doubling.
function double (number) {
return number * 2;
}
And use it like
function doubleNumbers (numbers) {
const doubledNumbers = [];
for (let i = 0; i < numbers.length; i++) {
doubledNumbers.push(double(numbers[i]));
}
return doubledNumbers
}
But as I say, I want to be able to do other stuff. So let’s just hand the doubledNumbers
function that double
function:
function doubleNumbers (numbers, doubleFunction) {
const doubledNumbers = [];
for (let i = 0; i < numbers.length; i++) {
doubledNumbers.push(doubleFunction(numbers[i]));
}
return doubledNumbers
}
Now I can do doubleNumbers([1,2,3], double)
– I’m giving it that double function I defined. But that could be any function. So let’s change the names. It isn’t doubling numbers if I give it a triple
or a quadruple
or a square
function for example, so doubleNumbers
is a bit of a daft name. Let’s call it map
.
function map (array, func) {
const outputArray = [];
for (let i = 0; i < array.length; i++) {
outputArray.push(func(array[i]));
}
return outputArray
}
array
is now any array. func
is now any function. Handily, JS provides this out of the box:
myArray.map(myFunction);