phurst-so
phurst-so

Reputation: 386

Struggling to Understand the Parameter Content when using .map on Function Expressions

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.

Upvotes: 1

Views: 51

Answers (3)

guest271314
guest271314

Reputation: 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?

Upvotes: 1

Walter Monecke
Walter Monecke

Reputation: 2558

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.

Upvotes: 1

spanky
spanky

Reputation: 2870

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;
};

Upvotes: 1

Related Questions