Web Developer Interview Preparation

Map( ) function

Definition The map() function The benefit of using the map() is immutability. Therefore it avoids changing the original array, while ‘for’ and ‘forEach’ transform the original array. Example 1 Let’s take an array and assign it to a new array.

var myArr = [5,6,7]
var newArr = myArr.map(function(item) {
    return item + 1;
});
console.log(newArr);
//Result: [6, 7, 8]
The map function returns an array that has been modified with the callback. It takes each one of items, adds 1 to it, and put the results of each one of those modifications into the new array. The original array stays the same. Example 2 Let’s make the previous callback function into a separate function.
var myArray = [5, 6, 7];
function inc(item) {
    return item + 1;
}
var modArr = myArr.map(inc);
console.log(modArr);
//Result: [6, 7, 8]
Example 3 The map() is returning a new array, without transforming the original data. We can chain some transformation together.
var myArr = [5,6,7]
function inc(item){
   return item + 1;
}
function square(item) {
   return item * item;
}
var modArr = myArray.map(inc).map(square);
console.log(modArr);
// Result: [36, 49, 64]
We can take one of the transformation, and the send it as the result to another transformation. We are calling the map() twice, 1st, we increment each of the elements in myArr. 2nd, we take each of those elements and multiplying them by themselves. We chain the two different transformations together without changing the original array. Next time, we will discuss the importance of immutability with the map(). Reference Show me how to use the map function. Mastering Web developer Interview Code – Ray Villalobos, Lynda.com LINK]]>

Leave a Reply

Your email address will not be published. Required fields are marked *