1

So I'm looking at function expressions.

This is the code I'm playing with:

var modifiedNames = [ "Thomas Meeks",
                      "Gregg Pollack",
                      "Christine Wong",
                      "Dan McGaw" ];

modifiedNames.map(function(cheese) {
  alert("Yo, " + cheese + "!");
});

It works fine but I'm having trouble understanding part of it. I grasp what .map is doing but the parameter is really throwing me. How is the parameter collecting the array's information? I called it cheese as that's just my go-to test word.

I have read a couple of explanations but I'm just not grasping it, hoping somebody here could simplify the explanation somewhat. Thank you.

phurst-so
  • 386
  • 5
  • 15

3 Answers3

1

You're passing the function to .map(), which then runs a loop, and invokes the function on every iteration, passing it the current item.

Think of it like this:

for (var i = 0; i < array.length; i++) {
  callback(array[i]);
}

Here array is the Array on which you called .map(), and callback is the function you passed in.

This isn't so mysterious now. It's just calling your function in a loop.

Of course, .map() does more work than this and passes more args, but this shows how the parameter gets populated.


A somewhat more complete implementation of a map would look like this:

Array.prototype.myMap = function(callback, thisArg) {
  var result = new Array(this.length);

  for (var i = 0; i < this.length; i++) {
    if (i in this) {
      result[i] = callback.call(thisArg, this[i], i, this);
    }
  }
  return result;
};
spanky
  • 2,768
  • 8
  • 9
  • Okay well the complex version lost me completely :D But I think I got it from your for loops example. So basically my 'cheese' is your 'i' right? @spanky – phurst-so Aug 21 '17 at 11:52
  • @11- Yes, except that the `i` is the index, but the `array[i]` is passed to your `cheese`. In other words, it's taking index `i` from `array` and passing it to your function's `cheese` parameter. – spanky Aug 21 '17 at 14:30
1

Are you asking how exactly this is working internally?

.map is using a for loop behind the scenes and passing each element within the array to the cheese pointer. So cheese will be "Thomas Meeks" and it will alert it and then continue on and on.

Walter Monecke
  • 2,386
  • 1
  • 19
  • 52
1

How is the parameter collecting the array's information? I called it cheese as that's just my go-to test word.

cheese is the named function parameter, which defines the passed parameter identifier within the scope of the function. The same as

function fn(cheese) {
  console.log(cheese)
}

fn("and crackers");

Or using .map()

["and crackers"].map(fn);

See also Why does .then() chained to Promise.resolve() allow const declaration to be reassigned?

guest271314
  • 1
  • 15
  • 104
  • 177