JavaScript map method

By on

What’s going on under the hood of the JavaScript map method? Well the output of the map method is a copy of the original array with the applied with the callback function. So, for example in the originalArray:

  var originalArray = [ 1, 2, 3, 4, 5 ];

we want the end product array elements to each be multiplied by 2, or:

  // [ 2, 4, 6, 8, 10 ];

In the for loop inside the timesTwo function this is how it would be done:

var timesTwo = function(array) {
  var timesTwoArray = [];
  for(var i = 0; i < array.length; i++) {
    timesTwoArray.push(array[i] * 2);
  }
  return timesTwoArray;
}

  console.log(timesTwo(originalArray));
  // [ 2, 4, 6, 8, 10 ]

For the map method, a callback function is needed in the argument to get the same result:

var timesTwoArray = originalArray.map(function(num){
  return num * 2;
});

console.log(timesTwoArray);
// [ 2, 4, 6, 8, 10 ]

Here’s how it looks like under the hood:

Array.prototype.map = function(callback){
  var result = [];
  for(var i = 0; i < this.length; i++){
    result.push(callback(this[i]));
  }
  return result;
}

var timesTwoFunc = function(num){
  return num * 2;
};

var timesTwoArray = originalArray.map(timesTwoFunc);

console.log(timesTwoArray);
// [ 2, 4, 6, 8, 10 ]

<p class=store> Feedback </p>