The Map function

Learn Javascript concepts in a tiny amount of time!

Today's lesson is about the map function.

What is Map ?

The map function is a functional-inspired function that applies a given function to every element of an Array.

How do you use it ?

const array = [10, 11, 12, 13, 14];
const fn = element => element * 2;

const resultArray = array.map(element => fn(element))

You first need an array, then a callback. You chain the map call on your array and pass the callback as the first argument of the function.

Signature

The map function can take up to two parameters.

callback

The callback is a function that will be call on every element of the array. It can take up to 3 parameters.

element

This is the current element from the array. In our example, it will consecutively take the value 10, then 11, then 12 and so on until the end of the array.

index

The index correspond to the current index of the internal loop of the function. As for the element, it will consecutively take the value 0, then 1, then 2 and so on until the end of the array.

array

The third and last argument is a duplicate of the array the map function is applied to. In out example, array will equal [10, 11, 12, 13, 14] every loop.

this

You can bind a custom value for the this context of the callback.

// Our new this
const context = {
  x: 0,
  y: 1
}
const array = [10, 11, 12, 13, 14];

const fn = function (element) {
  console.log(this) // this = context
  return element * 2
};

//                                Here, we set this to our context
const resultArray = array.map(element => fn(element), context)

The output here will be replaced by the value of the context variable.

Please note that this feature will only work when using the function syntax of function (and not the ES6+ syntax using arrows).

Tips and tricks

  • The function ensure that every call is executed in the same order of the array.
  • The function always return a new array.
  • If you don't need the resulting array, use the forEach function instead.
  • Explicitly specify function arguments. Parameters can conflicts if the callback change its signature. [source]