Dasphillipbrau
Dasphillipbrau

Reputation: 592

Having trouble understanding callback functions in JS

So I'm currently refreshing my JS knowledge and the bit about callback functions is confusing me.

This is basically a "grammar" question, I'm noticing in the examples of the exercises I'm seeing that the callback always uses an argument that is never specified in the code, and the program still makes it work.

Example:

const numbers = [1, 2, 3, 4, 5]; 

const bigNumbers = numbers.map(number => {
  return number * 10;
});

see "numbers" and "number", they're both different variables, so how is the program recognizing that "number" refers to the singular data inside of the array?

My problem is that I feel like the "number" variable comes out of nowhere, yet the program seems to know exactly what it does.

Upvotes: -1

Views: 53

Answers (2)

Ying Zuo
Ying Zuo

Reputation: 483

You can consider a callback as just a regular function being called after something happens. The map function is one of the most useful functions of an array. Basically, it loops through each value in the array and uses the value being returned instead of the original value. The best part of it is that it doesn't modify the original array.

Going back to the function you asked about. It may be easier to understand with the ES5 syntax. As the map loops through each element in the array, it passes the element as the first input parameter in the callback function, which is the variable number, and so it's available inside the function.

var bigNumbers = numbers.map(function(number){
  return number * 10;
});

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371193

The callback and its arguments are handled by Array.prototype.map internally. To see how it might work yourself, you can define your own function that does something similar, and calls a callback that's passed to it:

function myMap(callback) {
  const inputArr = this;
  const newArr = [];
  for (let i = 0; i < inputArr.length; i++) {
    newArr.push(
      callback(inputArr[i], i, inputArr)
    );
  }
  return newArr;
}

const numbers = [1, 2, 3, 4, 5]; 

const bigNumbers = myMap.call(numbers, number => number * 10);
console.log(bigNumbers);

The number argument doesn't come out of nowhere - it's an argument you define for the callback function with, which (for Array.prototype.map) the spec guarantees to correspond to the item in the array that's being iterated over. (You can use as many or as few arguments as you wish)

Upvotes: 1

Related Questions