Iterate over Arrays with map - Question

Iterate over Arrays with map - Question
0

#1

var oldArray = [1, 2, 3];
var timesFour = oldArray.map(function(val){
return val * 4;
});
console.log(timesFour); // returns [4, 8, 12]
console.log(oldArray); // returns [1, 2, 3]

My question is, why is the word ‘function’ in there after the first bracket? What’s it for?


#2

The function part is the “callback” that is required for the `.map method.

According to MDN, here’s a description the .map() method.

The map() method creates a new array with the results of calling a provided function on every element in this array.

In sum, it is a function that you use to iterate over your elements. In the code example you gave, you will multiply by 4 on each element of the oldArray variable. I hope that helps.

The function name doesn’t actually have to be there. You can define a function and then pass it into the .map() method.

var oldArray = [1, 2, 3];
var fourTimes = function(val) {
  return val * 4;
};
var timesFour = oldArray.map(fourTimes);
console.log(timesFour); // returns [4, 8, 12]
console.log(oldArray);  // returns [1, 2, 3]

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map


#3

Hi @saf94

There are some ‘methods’ already known to JavaScript, map being one of them. Once you master functions and objects in JavaScript this will make more sense but for the time being try to hang in there.

Methods (a method is a ‘special’ kind of function :slight_smile: ) or indeed functions can be passed parameters. In your example map is accepting an anonymous function (the function doesn’t have a name) as a parameter. It then runs what is inside the function, which in this case is the passed value(val) times four. Map is the method that, you guessed it…maps, each value from the original old array that then in turn is multiplied by four.

Finally I would recommend reading through this short explanation on functions. http://www.w3schools.com/js/js_function_parameters.asp

Good luck and have fun! :smiley:


#4

Ohh ok, got it. Thanks so much both of you guys for your explanations