JavaScript Array Operators: MAP
In this new series, you will learn everything about the different JavaScript operators. The first episode is all about the MAP operator. This operator can only be applied to arrays. JavaScript is undoubtedly on the rise. It has pretty much always been the engine for webpages, but with the introduction of JavaScript Frameworks like Angular, VueJS, ReactJS and Backend Frameworks like NodeJS the usage and adoption skyrocketed.
JavaScript arrays are used to store multiple values in a single variable. - Source
Description
The map operator creates and returns a new array with the updated values. You can use the values from the original array as data in the function body. On every object in the array the map function is called and returned.
You can achieve the same desired result with a forEach loop, but the map operator is much more compact and readable. At least in my opinion.
Usage
In the following example, we will use the map operator to triple the values from the original array and assign the newly created array to the resultArray. Keep in mind that the originalArray is not changed.
const originalArray = [1, 2, 3];
// call map with a function
const resultArray = originalArray.map(x => x * 3);
console.log(resultArray);
// expected output: Array [3, 6, 9]
You should not use the map operator when you are not planning to use the returned array or if you don't pass a function to the map operator. In this case, go for the forEach or for-of instead.
Parameters
The map operator supports multiple parameters.
arr.map(callback(currentValue[, index[, array]]) {
// return element for newArray, after executing something
}[, thisArg]);
Find a list of parameters below.
callback
A function that is executed for every element in the array. Everytime this function is executed a new element gets added to the newArray.currentValue
The currentValue which is processed.index
[optional]
The current index in the original array.array
[optional]
The array map was called upon.
thisArg
[optional]
Value to use as this when executing callback.
Find more details here.