How is array map working without passing the parameter?

Viewed 324
const arr2 = arr.map(double)

How this is working without me passing the array item? I need to pass a parameter to function double: something like double(item).

let arr = [1, 2, 3, 4, 5]

function double(x) {
  return x * 2
}

const arr2 = arr.map(double)

const arr3 = arr.map(item => double(item))

console.log("arr2= ", arr2)
console.log("arr3= ", arr3)

Output:

arr2 = [2, 4, 6, 8, 10]

arr3 = [2, 4, 6, 8, 10]
3 Answers

You can understand things like this by reading the code of polyfills. Simplified example:

Array.prototype.myMap = function(callbackFn) {
  const arr = [];
  for (let i = 0; i < this.length; i++) {
    // call the callback function for every value of this array
    // and push the returned value into our resulting array
    arr.push(callbackFn(this[i], i, this));
  }
  return arr;
}

In your case:

// for arr2
callbackFn === function double(x) {
  return x * 2
}

// for arr3
callbackFn === (item) => double(item)

Please read the map documentation.

The map method pass 3 arguments to the provided callback: the current element, the index and the original array.

You'll find everything in the doc.

you pass a function to the map function so basically in arr3 map function you created a new anonymous function using the arrow syntax that activate the double function inside but you didn't gave it the actual item this happens inside the map function

let arr = [1, 2, 3, 4, 5]

function double(x) {
  return x * 2
}

const arr2 = arr.map(double)

const arr3 = arr.map(item => double(item)) // This is a new function that you created

console.log("arr2= ", arr2)
console.log("arr3= ", arr3)

Related